Android中Webviw加载H5页面调用本地相机拍照并显示在H5页面上

需求:用户点击拍摄,调取相机,拍照后,返回到H5页面,上传成功后,将照片加载到H5页面中。对于用户上传的照片,后台进行压缩,每张图片压缩到200kb左右即可,格式为png。

思路:首先找到WebView控件加载url地址,然后 mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new Js(), “jsObj”);

然后

class Js {
@JavascriptInterface
public void goAppCamera() {
openCarcme();//打开相机
}
}

最后在onActivityResult中获取到Bitmap,将Bitmap转换成Base64之后再调用setPlatformType方法加载Url,话不多说直接上代码。

package camerademo.com.camerademo;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MainActivity extends Activity {


    private WebView mWebView;
    private ValueCallback mUploadMessage; //表单的数据信息


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mWebView = (WebView) findViewById(R.id.web_view);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebViewClient(new MyWebViewClient(this));
        mWebView.loadUrl("http://10.1.21.23:8080/view/demo/inputCamera.html");
        mWebView.getSettings().setJavaScriptEnabled(true);
        //在Js类里实现javascript想调用的方法(H5调用android),"jsObj"就是这个接口的别名
        mWebView.addJavascriptInterface(new Js(), "jsObj");

    }

    private class MyWebChromeClient extends WebChromeClient {

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            if (mUploadMessage != null)
                return;
            mUploadMessage = uploadMsg;
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }
    }

    private class MyWebViewClient extends WebViewClient {
        private Context mContext;

        public MyWebViewClient(Context context) {
            super();
            mContext = context;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }

    class Js {
        @JavascriptInterface
        public void goAppCamera() {
            openCarcme();
        }
    }

    /**
     * 打开相机
     */
    private void openCarcme() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);
    }

    public void setPlatformType(final String result) {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
            //android调用H5代码
                mWebView.loadUrl("javascript: cameraResult('"+ result.toString() + "')");
            }
        }, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 1 ) {
            //部分手机获取uri为空,则需要从bundle中获取Bitmap
            Uri uri = intent.getData();
            if(uri == null){
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Bitmap  bitmap = (Bitmap) bundle.get("data"); //get bitmap
                    Bitmap compressBitmap = compressImage(bitmap);
                    Log.d("it520", "bitmapToBase64被调了...");
                    String str = bitmapToBase64(compressBitmap);
                    setPlatformType(str);
                }
            }else {
                Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
                Bitmap compressBitmap = compressImage(bitmap);
                Log.d("it520", "else中的bitmapToBase64被调了...");
                String str = bitmapToBase64(compressBitmap);
                setPlatformType(str);

            }
        }
    }

    /**
     * 图片压缩
     * @param image
     * @return
     */
    public Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
//因为获取到的ByteArrayOutputStream大小基本为50几kb,所以不用压缩,所以以下代码注释掉       
//        int options = 90;
//        while (baos.toByteArray().length / 1024 > 200) {// 循环判断如果压缩后图片是否大于200kb,大于继续压缩
//            baos.reset(); // 重置baos即清空baos
//            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options,把压缩后的数据存放到baos中
//            options -= 10;// 每次都减少10
//        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    // bitmap转base64
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = "data:image/png;base64,";//必须加上“data:image/png;base64”图片的数据格式H5才能识别出来
        ByteArrayOutputStream bos = null;
        try {
            if (null != bitmap) {
                bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);// 将bitmap放入字节数组流中
                bos.flush();// 将bos流缓存在内存中的数据全部输出,清空缓存
                bos.close();
                byte[] bitmapByte = bos.toByteArray();
                result += Base64.encodeToString(bitmapByte, Base64.DEFAULT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.d("it520", "result=" + result);
        Log.d("it520", "size=" + bos.toByteArray().length / 1024);//获取ByteArrayOutputStream的大小,单位kb,
        return result;
    }

    /**
     * base64转Bitmap
     * @param base64String
     * @return
     */
    public static Bitmap base64ToBitmap(String base64String) {
        byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;
    }

}

附图为h5部分代码
Android中Webviw加载H5页面调用本地相机拍照并显示在H5页面上_第1张图片

你可能感兴趣的:(webview,android)