图片相册工具类

首先是主要的工具类

public class PhoneCameraUtil {
    public static final int PICK_FROM_CAMERA = 1;
    public static final int CROP_FROM_CAMERA = 2;
    public static final int PICK_FROM_FILE = 3;
    public static Uri imageCaptureUri;
    private File imgCaptureFile;
    private static final int MEDIA_TYPE_IMAGE = 1;

    private Activity mActivity;
    private Context mContext;
    private PhonePicListener picListener;

    public PhoneCameraUtil(Context context, Activity activity) {
        this.mActivity = activity;
        this.mContext = context;
    }

    public interface PhonePicListener {
        void instruct(int state, String data);
    }

    private DialogChoosePreview cameraAlert;

    public void dialogInit(View.OnClickListener clickListen) {
        if (cameraAlert == null) {
            cameraAlert = new DialogChoosePreview(mContext, clickListen);
        }
    }

    public void dialogDismiss() {
        if (cameraAlert != null) {
            cameraAlert.dismiss();
        }
    }

    public void dialogShow(String imgPath) {
        if (cameraAlert != null) {
            cameraAlert.setImgUrl(imgPath);
            cameraAlert.show();
        }
    }

    /**
     * 页面授权访问,
     *
     * @param requestCode 编号,
     * @param grantResults 权限组
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull int[] grantResults,
        PhonePicListener listener) {
        this.picListener = listener;
        switch (requestCode) {
            case 12:
                boolean permissionsIsAgree = false;// 许可
                if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    permissionsIsAgree = true;
                }
                if ((grantResults[0] == PackageManager.PERMISSION_GRANTED) && permissionsIsAgree) {
                    this.getImageCameraPermission(); // 许可
                } else {
                    if (picListener != null) {
                        picListener.instruct(1, "很遗憾你把相机权限禁用了。");
                    }
                }
                break;
            case 11:
            case 10:
                if ((grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    this.getImageCameraPermission();// 许可
                } else {
                    // Permission Denied
                    if (picListener != null) {
                        picListener.instruct(1, "很遗憾你把相机权限禁用了。");
                    }
                }
                break;
            case 2:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    this.getImagePicture();
                } else {
                    // Permission Denied
                    if (picListener != null) {
                        picListener.instruct(1, "很遗憾你把相册权限禁用了。");
                    }
                }
                break;
            default:
        }
    }

    //页面Activity,返回处理,
    public void onActivityResult(int reqCode, int resultCode, Intent data,
        PhonePicListener listener) {
        this.picListener = listener;
        if (resultCode == Activity.RESULT_OK && reqCode == PICK_FROM_CAMERA) {
            this.returnZipPicture(data, 1);
        } else if (resultCode == Activity.RESULT_OK && reqCode == PICK_FROM_FILE) {
            this.returnZipPicture(data, 2);
        } else if (resultCode == Activity.RESULT_OK && reqCode == CROP_FROM_CAMERA) {
            if (picListener != null) {
                picListener.instruct(1, imgCaptureFile.getAbsolutePath());
            }
        }
    }

    //获取相册图片路径,
    public void getPhonePicCamera(Intent data, PhonePicListener listener) {
        this.picListener = listener;
        this.returnZipPicture(data, 1);
    }

    /**
     * 相册路径处理
     *
     * @param data 返回数据
     * @param listener 回调
     */
    public void getPhonePicAlbum(Intent data, PhonePicListener listener) {
        this.picListener = listener;
        this.returnZipPicture(data, 2);
    }

    private int returnPicType = 0;

    /**
     * 图片处理方式,
     *
     * @param type 0(默认压缩),1裁切
     */
    public void setReturnPicType(int type) {
        this.returnPicType = type;
    }

    /**
     * 原图路径压缩,返回压缩后路径
     *
     * @param data 原图路径
     */
    private void returnZipPicture(Intent data, int type) {
        String filePathImg = null;
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) && type == 1) {
            filePathImg = imgCaptureFile.getAbsolutePath();
            imgCaptureFile = null;
        } else {
            if (type==1){
                if (data != null) {
                    imageCaptureUri = data.getData();
                }
                if (imageCaptureUri!=null){
                    filePathImg = imageCaptureUri.getPath();
                }
            }else if (type==2&&data != null && data.getData() != null){
                filePathImg = getPath(data.getData());
            }
        }
        //获取相册图片路径,
        imageCaptureUri = null;
        if (!isPicture(filePathImg)) {
            if (picListener != null) {
                picListener.instruct(0, "请选择png或者jpg格式图片");
            }
            return;
        }
        try {
            File file = new File(filePathImg);
            if (file.length() > (1024 * 50) || returnPicType == 0) {
                //fileSizeSmallCrop(filePathImg,file,data,1);
                fileSizeSmallLuBan(filePathImg);
            } else {
                //ToastUtils.getInstance().msg("1M小于文件大小"+file.length());
                if (picListener != null) {
                    picListener.instruct(1, filePathImg);
                }
            }
        } catch (Exception e) {
            if (picListener != null) {
                picListener.instruct(0, "图片路径异常!!!");
            }
            e.printStackTrace();
        }
    }

    /**
     * 裁切图片
     *
     * @param filePathImg 图片路径
     * @param cropType 1系统裁切,2,裁切Activity
     */
    private void fileSizeSmallCrop(String filePathImg, File file, Intent data, int cropType) {
            //调取系统裁切方法,尺寸不管用,
            //    File compressedImage = new Compressor(mActivity).setMaxWidth(640)
            //        .setMaxHeight(480)
            //        .setQuality(100)
            //        .setCompressFormat(Bitmap.CompressFormat.WEBP)
            //        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
            //            Environment.DIRECTORY_PICTURES).getAbsolutePath())
            //        .compressToFile(file);
            //compressedImage.getAbsolutePath()
            //    if (picListener != null) {
            //        picListener.instruct(1,filePathImg );
            //    }
            //} else if (returnPicType == 1) {
            Uri uriOut;
            Uri uriFile;
            if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)) {
                //改变Uri  com.xx.xxx.fileProvider注意和xml中的一致
                imgCaptureFile = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/"
                        + ConstantValues.FOLDER
                        + "/"
                        + System.currentTimeMillis()
                        + ".jpg");
                imgCaptureFile.getParentFile().mkdirs();
                uriOut = Uri.fromFile(imgCaptureFile);
                uriFile = FileProvider.getUriForFile(mActivity, ConstantValues.FILE_PROVIDER, file);
            } else {
                imgCaptureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
                uriOut = Uri.fromFile(imgCaptureFile);
                if (data != null && data.getData() != null) {
                    uriFile = data.getData();
                } else {
                    uriFile = Uri.fromFile(file);
                }
            }
            //调用系统照片的裁剪功能,修改编辑头像的选择模式(适配Android7.0)
            Intent intent = new Intent("com.android.camera.action.CROP");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            intent.setDataAndType(uriFile, "image/*");
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", "true");
            intent.putExtra("scale", false);
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX,outputY 是剪裁图片的宽高
            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("return-data", false);
            intent.putExtra("noFaceDetection", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uriOut);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            mActivity.startActivityForResult(intent, CROP_FROM_CAMERA);

    }

    private void fileSizeSmallLuBan(final String filePathYt) {
        Luban.with(mActivity).load(filePathYt)                                   // 传人要压缩的图片列表
            .ignoreBy(450)                                  // 忽略不压缩图片的大小
            //.setTargetDir(imgpath)                        // 设置压缩后文件存储位置
            .setCompressListener(new OnCompressListener() { //设置回调
                @Override public void onStart() {
                    if (picListener != null) {
                        picListener.instruct(0, "图片加载中");
                    }
                }

                @Override public void onSuccess(File file) {
                    //压缩成功后调用,返回压缩后的图片文件
                    if (picListener != null) {
                        picListener.instruct(1, file.getAbsolutePath());
                    }
                }

                @Override public void onError(Throwable e) {
                    if (picListener != null) {
                        picListener.instruct(2, "图片尺寸过大");
                    }
                    //当压缩过程出现问题时调用
                }
            }).launch();    //启动压缩
    }


    public String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "KB";//Byte
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    public String saveImageToGallery(Context context, Bitmap bmp) {
        String imgpath =
            Environment.getExternalStorageDirectory().toString() + "/" + ConstantValues.FOLDER + "/";
        // 首先保存图片
        File appDir =
            new File(Environment.getExternalStorageDirectory().toString(), ConstantValues.FOLDER);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + "sc.jpg";
        imgpath += fileName;
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 1, fos);
            fos.flush();
            fos.close();
            bmp.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //在手机相册中显示刚拍摄的图片
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        mActivity.sendBroadcast(mediaScanIntent);
        // 最后通知图库更新
        //        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
        //                Uri.parse("file://" + imgpath)));
        //方法2
        ////        Uri imageUri = data.getData();
        ////        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        ////        Cursor c = mActivity.getContentResolver().query(imageUri,
        ////                filePathColumns, null, null, null);
        ////        c.moveToFirst();
        ////        int columnIndex = c.getColumnIndex(filePathColumns[0]);
        ////        String imagePath = c.getString(columnIndex);
        ////        c.close();
        //
        //// 设置参数
        //        BitmapFactory.Options options = new BitmapFactory.Options();
        //        options.inJustDecodeBounds = true; // 只获取图片的大小信息,而不是将整张图片载入在内存中,避免内存溢出
        //        BitmapFactory.decodeFile(imagePath, options);
        //        int height = options.outHeight;
        //        int width = options.outWidth;
        //        int inSampleSize = 2; // 默认像素压缩比例,压缩为原图的1/2
        //        int minLen = Math.min(height, width); // 原图的最小边长
        //        if (minLen > 100) { // 如果原始图像的最小边长大于100dp(此处单位我认为是dp,而非px)
        //            float ratio = (float) minLen / 100.0f; // 计算像素压缩比例
        //            inSampleSize = (int) ratio;
        //        }
        //        options.inJustDecodeBounds = false; // 计算好压缩比例后,这次可以去加载原图了
        //        options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
        //        Bitmap bmp = BitmapFactory.decodeFile(imagePath, options); // 解码文件
        //        // 首先保存图片
        //        String imgpath = Environment.getExternalStorageDirectory().toString() + "/" + imgFolder + "/";
        //        File appDir = new File(Environment.getExternalStorageDirectory().toString(), imgFolder);
        //        if (!appDir.exists()) {
        //            appDir.mkdir();
        //        }
        //        String fileName = System.currentTimeMillis() + "sc.jpg";
        //        File file = new File(appDir, fileName);
        //        imgpath += fileName;
        //        try {
        //            FileOutputStream fos = new FileOutputStream(file);
        //            //质量压缩 100 不压缩,0-100
        //            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        //            fos.flush();
        //            fos.close();
        //            bmp.recycle();
        //        } catch (FileNotFoundException e) {
        //            e.printStackTrace();
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        }
        //        // 其次把文件插入到系统图库
        //        try {
        //            MediaStore.Images.Media.insertImage(mActivity.getContentResolver(),
        //                    file.getAbsolutePath(), fileName, null);
        //        } catch (FileNotFoundException e) {
        //            e.printStackTrace();
        //        }
        //        //在手机相册中显示刚拍摄的图片
        //        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        //        Uri contentUri = Uri.fromFile(file);
        //        mediaScanIntent.setData(contentUri);
        //        mActivity.sendBroadcast(mediaScanIntent);
        ////        Log.w("TAG", "size: " + bm.getByteCount() + " width: " + bm.getWidth() + " heigth:" + bm.getHeight()); // 输出
        //        return imgpath;
        return imgpath;
    }

    private void getImageCamera() {
        imageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)) {
            //通过FileProvider创建一个content类型的Uri
            //添加权限,添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        //            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        //将拍取的照片保存到指定URI
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
        mActivity.startActivityForResult(intent, PICK_FROM_CAMERA);
    }

    /**
     * 获取权限 Permission
     */
    public void getImageCameraPermission() {
        //判断版本
        if (Build.VERSION.SDK_INT >= 23) {
            //检查权限是否被授予:
            int checkCallPhonePermission =
                ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA);
            int hasExternalPermission = ContextCompat.checkSelfPermission(mActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //申请权限
                if (hasExternalPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mActivity, new String[] {
                        Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 12);
                } else {
                    ActivityCompat.requestPermissions(mActivity,
                        new String[] { Manifest.permission.CAMERA }, 10);
                }
            } else {
                if (hasExternalPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mActivity,
                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 11);
                } else {
                    //权限已经被授予
                    getImageCamera();
                }
            }
        } else {
            getImageCamera();
        }
    }

    //从图库获取图片
    public void getImagePicture() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(mActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(mActivity,
                    new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 2);
            } else {
                openPictureFiles();
            }
        } else {
            openPictureFiles();
        }
    }

    //去手机相册
    private void openPictureFiles() {
        // pick from file
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        mActivity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
            PICK_FROM_FILE);
          /*Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image*//**//**//**//*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, PICK_FROM_FILE);*/
        //打开选择图片的界面
        //        Intent intent = new Intent(Intent.ACTION_PICK);
        //        intent.setType("image/*");//相片类型
        //        mActivity.startActivityForResult(intent, PICK_FROM_FILE);
    }

    private boolean isPicture(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        } else if (filePath.endsWith(".png")) {
            return true;
        } else if (filePath.endsWith(".jpg")) {
            return true;
        } else if (filePath.endsWith(".jpeg")) {
            return true;
        }
        return false;
    }

    private String getDocumentId(Uri uri) {
        String res = null;
        try {
            Class<?> c = Class.forName("android.provider.DocumentsContract");
            Method get = c.getMethod("getDocumentId", Uri.class);
            res = (String) get.invoke(c, uri);
        } catch (Exception ignored) {
            ignored.getMessage();
        }
        return res;
    }

    @SuppressLint("NewApi") public String getPath(final Uri uri) {
        // final boolean mIsKitKat = Build.VERSION.SDK_INT >=
        // Build.VERSION_CODES.KITKAT;
        //
        // if (mIsKitKat
        // && DocumentsContract.isDocumentUri(MainAixinActivity.this, uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        } // MediaProvider  handle non-primary volumes
        else if (isMediaDocument(uri)) {
            final String docId = getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };
            return getDataColumn(mContext, contentUri, selection, selectionArgs);
        } else if (isDownloadsDocument(uri)) {

            final String id = getDocumentId(uri);
            final Uri contentUri =
                ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(mContext, contentUri, null, null);
        } else if (isDownloadsDocument(uri)) {

            final String id = getDocumentId(uri);
            final Uri contentUri =
                ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(mContext, contentUri, null, null);
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {

            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            }
            return getDataColumn(mContext, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(mContext, uri, null, null);
        } else {
            return getRealPathFromUriMinusKitKat(mContext, uri);
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    private String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {
        Cursor cursor = null;
        String[] projection = {
            MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION
        };
        try {
            cursor =
                context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                return cursor.getString(columnIndex);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    private String getRealPathFromUriMinusKitKat(Context context, Uri uri) {
        Cursor cursor = null;
        try {
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //路径信息  picturePath;
                return cursor.getString(columnIndex);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    private boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 加载本地路径图片
     *
     * @param strPicPath 图片路径
     * @return 路径图片
     */
    public Bitmap getDeal(String strPicPath) throws Exception {
        Bitmap bitmap = null;
        Bitmap rBitmap = null;
        FileInputStream fs = null;
        try {
            BitmapFactory.Options bfOptions = new BitmapFactory.Options();
            bfOptions.inDither = false;
            bfOptions.inPurgeable = true;

            bfOptions.inInputShareable = true;
            bfOptions.inTempStorage = new byte[12 * 1024];

            File file = new File(strPicPath);

            if (file.exists()) {

                fs = new FileInputStream(file);
                rBitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
                if (rBitmap != null) {
                    int iheight = 320;
                    int iwidth = 480;

                    if (rBitmap.getHeight() > 768) {
                        iheight = 320;
                    }

                    if (rBitmap.getWidth() > 1024) {
                        iwidth = 480;
                    }

                    bitmap = reduce(rBitmap, iwidth, iheight, true);
                    bitmap = compressBmpFromBmp(bitmap);
                    //                    FileUtils.mkDir(FileUtils.SDCARD_PATH + "/nameFolder/");
                    //                    FileOutputStream fos = new FileOutputStream(
                    //                            FileUtils.SDCARD_PATH + "/nameFolder/img.jpg");
                    //                    bitmap.compress(CompressFormat.JPEG, 100, fos);
                    //                    fos.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fs != null) {
                fs.close();
            }
            if (rBitmap != null) {
                if (!rBitmap.isRecycled()) {
                    rBitmap.recycle();
                    rBitmap = null;
                }
            }
        }
        return bitmap;
    }

    private Bitmap compressBmpFromBmp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 90;
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 200) {
            if (options - 10 > 0) {
                options -= 10;
            } else {
                break;
            }
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    /**
     * 压缩图片
     *
     * @param bitmap 源图片
     * @param width 想要的宽度
     * @param height 想要的高度
     * @param isAdjust 是否自动调整尺寸, true图片就不会拉伸,false严格按照你的尺寸压缩
     * @return Bitmap
     */
    public Bitmap reduce(Bitmap bitmap, int width, int height, boolean isAdjust) {
        // 如果想要的宽度和高度都比源图片小,就不压缩了,直接返回原图
        if (bitmap.getWidth() < width && bitmap.getHeight() < height) {
            return bitmap;
        }
        // 根据想要的尺寸精确计算压缩比例, 方法详解:public BigDecimal divide(BigDecimal divisor,
        // int scale, int roundingMode);
        // scale表示要保留的小数位, roundingMode表示如何处理多余的小数位,BigDecimal.ROUND_DOWN表示自动舍弃
        float sx = new BigDecimal(width).divide(new BigDecimal(bitmap.getWidth()), 4,
            BigDecimal.ROUND_DOWN).floatValue();
        float sy = new BigDecimal(height).divide(new BigDecimal(bitmap.getHeight()), 4,
            BigDecimal.ROUND_DOWN).floatValue();
        if (isAdjust) {// 如果想自动调整比例,不至于图片会拉伸
            sx = (sx < sy ? sx : sy);
            sy = sx;// 哪个比例小一点,就用哪个比例
        }
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy);// 调用api中的方法进行压缩,就大功告成了
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
            true);
    }

    /**
     * Create a file Uri for saving an image or video
     */
    private Uri getOutputMediaFileUri(int type) {
        //解决Android 7.0之后的Uri安全问题
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imgCaptureFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/"
                + ConstantValues.FOLDER
                + "/"
                + System.currentTimeMillis()
                + ".jpg");
            imgCaptureFile.getParentFile().mkdirs();
            //改变Uri  com.xx.xxx.fileProvider注意和xml中的一致
            uri = FileProvider.getUriForFile(mActivity, ConstantValues.FILE_PROVIDER, imgCaptureFile);
        } else {
            uri = Uri.fromFile(getOutputMediaFile(type));
        }
        return uri;
    }

    public String getFileAddress(int state, String appName, Context mContext) {
        String Address = "";
        if (GetSDState()) {
            Address = Environment.getExternalStorageDirectory().getPath() + "/" + appName + "/";
        } else {
            Address = mContext.getCacheDir().getAbsolutePath() + "/" + appName + "/";
        }
        switch (state) {
            case 1:
                Address = Address + "cache1/";
                break;
            case 2:
                Address = Address + "video/";
                break;
            case 3:
                Address = Address + "voice/";
                break;
            case 4:
                Address = Address + "file/";
                break;
            case 5:
                Address = Address + "photos/";
                break;
            default:
                Address = Address + "cache/";
                break;
        }
        File baseFile = new File(Address);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        return Address;
    }

    // 返回是否有SD卡
    private boolean GetSDState() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    /**
     * Create a File for saving an image or video
     */
    @SuppressLint("SimpleDateFormat") private File getOutputMediaFile(int type) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaFile = null;
        if (GetSDState()) {// ----判断是否有SD卡
            File mediaStorageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                ConstantValues.FOLDER);
            // This location works best if you want the created images to be shared
            // between applications and persist after your app has been uninstalled.
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    // Log.d("MyCameraApp", "failed to create directory");
                    return null;
                }
            }
            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            if (type == MEDIA_TYPE_IMAGE) {
                mediaFile = new File(
                    mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
            }
        } else {
            mediaFile = new File(getFileAddress(type, ConstantValues.FOLDER, mContext),
                ConstantValues.FOLDER + System.currentTimeMillis() + ".jpg");
        }
        return mediaFile;
    }
}

弹出的Dialog

public class DialogChoosePreview {
    private Dialog dialog;

    private View.OnClickListener clickListen;
    private Context mCtx;
    private View btnPreview;

    public DialogChoosePreview(Context context,View.OnClickListener onClickListener){
        this.mCtx=context;
        this.clickListen = onClickListener;
        initDialog();
    }
    public void show(){
        if (dialog==null){
            initDialog();
        }
        if (dialog.isShowing()){
            dialog.dismiss();
        }else{
            dialog.show();
        }
    }
    public void dismiss(){
        if (dialog!=null){
            dialog.dismiss();
        }
    }
    private void initDialog(){
        //        alertDialog = new AlertDialog.Builder(context, R.style.).create();
        //        alertDialog.setCancelable(true);
        //        alertDialog.setCanceledOnTouchOutside(true);
        //        Window win = alertDialog.getWindow();
        //        WindowManager.LayoutParams lp = win.getAttributes();
        //        win.setGravity(Gravity.FILL | Gravity.BOTTOM);
        //        win.setAttributes(lp);
        //        win.setContentView(R.layout.win_dialog_camera);
        View win= LayoutInflater.from(mCtx).inflate(R.layout.dialog_update_avatar,null);
        dialog = new Dialog(mCtx, R.style.dialog_bottom);
        dialog.setCancelable(true);
        dialog.setContentView(win);
        dialog.setCanceledOnTouchOutside(true);
        btnPreview=win.findViewById(R.id.tvYuanTu);
        btnPreview.setVisibility(View.GONE);
        btnPreview.setOnClickListener(clickListen);
        win.findViewById(R.id.llContent).setOnClickListener(clickListen);
        TextView btnCamera=win.findViewById(R.id.tvPaiZhao);
        btnCamera.setTag("camera");
        btnCamera.setOnClickListener(clickListen);
        TextView btnAlbum=win.findViewById(R.id.tvXiangCe);
        btnAlbum.setTag("PhotoAlbum");
        btnAlbum.setOnClickListener(clickListen);
        TextView btnCancel=win.findViewById(R.id.tvClose);
        btnCancel.setTag("cancel");
        btnCancel.setOnClickListener(clickListen);

    }
    private String dataImgUrl;
    public void setImgUrl(String url){
        try {
            if (TextUtils.isEmpty(url)){
                btnPreview.setVisibility(View.GONE);
            }else{
                this.dataImgUrl=url;
                btnPreview.setVisibility(View.VISIBLE);
                btnPreview.setTag(dataImgUrl);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

弹出Dialog视图

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/straight_white_fill_10"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvPaiZhao"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="15dp"
            android:text="拍照"
            android:textSize="18dp"
            style="@style/text_title_14_black"/>

        <View
            style="@style/view_1dp_gray_heng"/>

        <TextView
            android:id="@+id/tvXiangCe"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="15dp"
            android:text="从相册中选择"
            android:textSize="18dp"
            style="@style/text_title_14_black"/>

        <View
            style="@style/view_1dp_gray_heng"/>
        <View
            style="@style/view_1dp_gray_heng"/>

        <TextView
            android:id="@+id/tvYuanTu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="15dp"
            android:text="查看原图"
            android:textSize="18dp"
            style="@style/text_title_14_black"/>
    </LinearLayout>

    <TextView
        android:id="@+id/tvClose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/straight_white_fill_10"
        android:gravity="center"
        android:padding="15dp"
        android:text="取消"
        android:textSize="18dp"
        style="@style/text_title_14_black2"/>
</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值