android之 h5调用系统相机和相册并显示

先上html界面的代码,放在assets里面就可以了,我也不太会html,所以随便写了点


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="Generator" content="EditPlus®">
    <meta name="Author" content="">
    <meta name="Keywords" content="">
    <meta name="Description" content="">
    <title>H5页面上传手机照片title>
head>
<body>
<script>

function previewFile1() {
        var img = document.getElementById("preview1");
        // 仅限上传单张图片
        var file =document.getElementById("demo1").files[0];
        var text2 = document.getElementById("text2");
        var reader  = new FileReader();
        reader.addEventListener("load", function () {
                img.src = reader.result;  // 存储在本地的图片的base64编码
        }, false);

        if (file) {
          reader.readAsDataURL(file);
        }
     }

     function previewFile2() {
        var img2 = document.getElementById("preview2");
        // 仅限上传单张图片
        var file2 = document.getElementById("demo2").files[0];
        var reader2  = new FileReader();
        reader2.addEventListener("load", function () {
                img2.src = reader2.result;  // 存储在本地的图片的base64编码
        }, false);

        if (file2) {
          reader2.readAsDataURL(file2);
        }
     }

script>
<form action="">
    <p>图片1: <input type="file" id="demo1" name="uploadImg1" onchange="previewFile1()"/>p>
    <p>图片2: <input type="file" id="demo2" name="uploadImg2" onchange="previewFile2()"/>p>
    <img id="preview1" src="" width="100" height="100"/>
    <br>
    <img id="preview2" src="" width="100" height="100"/>
form>
body>
html>

然后来看看java怎么做
主要是对webview进行操作

public void initWebView() {
        WebView webview = (WebView) findViewById(R.id.act_certification_webview);
        WebSettings webSettings = webview.getSettings();
        //设置WebView属性,能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webview.loadUrl("file:///android_asset/interact.html");
        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {//5.0+
                showDialog();
                mFilePathCallback = filePathCallback;
                return true;
            }

            //openFileChooser 方法是隐藏方法
            public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {// android 系统版本>4.1.1
                showDialog();
                mFilePathCallback = uploadMsg;
            }

            public void openFileChooser(ValueCallback uploadMsg) {//android 系统版本<3.0
                showDialog();
                mFilePathCallback = uploadMsg;
            }

            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {//android 系统版本3.0+
                showDialog();
                mFilePathCallback = uploadMsg;
            }

        });


    }

拍照和相册选择的弹窗

 private void showDialog() {
        NiceDialog
                .init()
                .setLayoutId(R.layout.dialog_choose_photo)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.setOnClickListener(R.id.dialog_choose_photo_takePhoto, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                autoObtainCameraPermission(1);
                            }


                        });

                        holder.setOnClickListener(R.id.dialog_choose_photo_gallery, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                autoObtainStoragePermission(1);

                            }
                        });
                    }
                })

                .setDimAmount(0.5f)
                .setShowBottom(false)
                .setAnimStyle(R.style.popwindow_center_style)
                .setMargin(30)
                .setOutCancel(true)
                .show(getSupportFragmentManager());
    }

先检查是否有权限

    public void autoObtainCameraPermission(int type) {
        this.type = type;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
//                ToastUtils.showToastCenter("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (CommonUtil.hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    imageUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri

                PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
            } else {
                ToastUtils.showToastCenter("设备没有SD卡!");
            }
        }
    }

收到照片的回调

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_CAMERA_REQUEST) {
//                cropImageUri = Uri.fromFile(fileCropUri);
//                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                Bitmap bitmapFromUri = PhotoUtils.getBitmapFromUri(imageUri, this);
                int bitmapDegree = getBitmapDegree(imageUri.getPath());
                Bitmap bitmap = rotateBitmapByDegree(bitmapFromUri, bitmapDegree);
                if (bitmap == null) {
                    showToastBottom("对不起,图片不正确!");
                    return;
                }
                try {
                    File fileIcon = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + "4.jpg");
                    saveBitmapToUri(bitmap, fileIcon.getAbsolutePath());
                    getbitmap(type, fileIcon.getPath(), bitmap);
                } catch (IOException e) {
                    showToastBottom("图片压缩异常");
                }

            } else if (CODE_GALLERY_REQUEST == requestCode) {
                if (hasSdcard()) {
//                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, mContext.getPackageName() + ".fileprovider", new File(newUri.getPath()));
                    }
                    int bitmapDegree = getBitmapDegree(newUri.getPath());

                    Bitmap bitmapFromUri = PhotoUtils.getBitmapFromUri(newUri, this);
                    if (bitmapFromUri == null) {
                        showToastBottom("对不起,图片不正确!");
                        return;
                    }
                    Bitmap bitmap = rotateBitmapByDegree(bitmapFromUri, bitmapDegree);
                    if (bitmap == null) {
                        showToastBottom("对不起,图片不正确!");
                        return;
                    }
                    try {
                        File fileIcon = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + "4.jpg");
                        saveBitmapToUri(bitmap, fileIcon.getAbsolutePath());
                        getbitmap(type, fileIcon.getPath(), bitmap);
                    } catch (IOException e) {
                        showToastBottom("图片压缩异常");
                    }
//                    PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);

                } else {
                    ToastUtils.showToastCenter("设备没有SD卡!");
                }
//            } else if (CODE_RESULT_REQUEST == requestCode) {
//                Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
//                if (bitmap != null && cropImageUri != null) {
//
////                    getbitmap(type, cropImageUri, bitmap);
//                }
            }
        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片的旋转角度
     */
    private int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片,并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;
        // 根据旋转角度,生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转,并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {

        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    /**
     * 把压缩后的bitmap转化为file;
     *
     * @param path;压缩后的file路径
     */
    private boolean saveBitmapToUri(Bitmap bitmap, String path)
            throws IOException {
        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                if (!file.createNewFile()) {
                    return false;
                }
            }
        }
        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);//100为压缩的品质,100为100%
        outStream.flush();
        outStream.close();
        return true;
    }

回调webview

   @Override
    protected void getbitmap(int type, String imagePath, Bitmap bitmap) {
        Uri uri = Uri.fromFile(new File(imagePath));
        if (Build.VERSION.SDK_INT > 18) {
            mFilePathCallback.onReceiveValue(new Uri[]{uri});
        } else {
            mFilePathCallback.onReceiveValue(uri);
        }

    }

来看效果图

你可能感兴趣的:(android)