Android 11 图片裁剪 兼容Android各版本

图片裁剪
使用方式调用launchpick,launchcamera

public class PhotoUtil {
    private static final String IMAGE_TYPES = "image/*";
    private static final String LOG_TAG = "PhotoUtil";


    private File mOnputFileClip = null;
    private File mOnputFileCamera = null;

    private int aspectX = 1;
    private int aspectY = 1;
    private int outputX = 800;
    private int outputY = 800;
    private ClipPhotoPathCallBack clipPhotoPathCallBack;

    private static class Single {
        private static PhotoUtil instance = new PhotoUtil();
    }

    public void setClipPhotoPathCallBack(ClipPhotoPathCallBack clipPhotoPathCallBack) {
        this.clipPhotoPathCallBack = clipPhotoPathCallBack;
    }

    private PhotoUtil() {
    }

    public static PhotoUtil getInstance() {
        return Single.instance;
    }

    public interface ClipPhotoPathCallBack {
        void clipPhotoPathSuccess(String path);

        void clipPhotoPathFailed(CGError error);
    }

    public void setCropParam(int aspectX, int aspectY, int outputX, int outputY) {
        this.aspectX = aspectX;
        this.aspectY = aspectY;
        this.outputX = outputX;
        this.outputY = outputY;
    }

    public void reqeustPhoto(int requestCode, Intent intent) {
        switch (requestCode) {
            case ConfigUtils.IMAGE_PICKER_CODE:
                File file = null;
                try {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = FileUtil.uriToFileApiQ(ContextUtils.getCurrentActivity(), intent.getData());
                    } else {
                        file = new File(FileUtil.getRealFilePath(ContextUtils.getCurrentActivity(), intent.getData()));
                    }
                    if (file != null&&file.length()>0) {
                        clipPhoto(file);
                    }else {
                        CGError cgError = CGError.FailedToClipPhoto;
                        cgError.setExtra("file is null");
                        if (clipPhotoPathCallBack != null)
                            clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                    }
                    LogUtil.terminal(new CGNormalReportLog.Builder(LOG_TAG, CGNormalReportLog.CORE_MODULE)
                            .module(CGNormalReportLog.CORE_MODULE).logType(CGLog.LogType.rum)
                            .logLevel(CGLog.LogLevel.d).methodName("IMAGE_PICKER_CODE").eTag("IMAGE_PICKER_CODE")
                            .eventParams("IMAGE_PICKER_CODE: file path = " + (file == null ? "null" : file.getAbsolutePath()))
                            .logs("IMAGE_PICKER_CODE success").build());
                } catch (Exception e) {
                    e.printStackTrace();
                    CGError cgError = CGError.FailedToClipPhoto;
                    cgError.setExtra("IMAGE_PICKER_CODE:" + e.toString());
                    if (clipPhotoPathCallBack != null)
                        clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                    LogUtil.terminal(new CGNormalReportLog.Builder(LOG_TAG, CGNormalReportLog.CORE_MODULE)
                            .module(CGNormalReportLog.CORE_MODULE).logType(CGLog.LogType.rum)
                            .logLevel(CGLog.LogLevel.e).methodName("IMAGE_PICKER_CODE").eTag("IMAGE_PICKER_CODE")
                            .eventParams("IMAGE_PICKER_CODE: file path = " + (file == null ? "null" : file.getAbsolutePath()))
                            .logs("IMAGE_PICKER_CODE cgError:" + cgError.toJsonString()).build());
                }
                break;
            case ConfigUtils.IMAGE_CROP_CODE:
                String message = "";
                String path = "";
                try {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        File file1 = null;
                        file1 = FileUtil.uriToFileApiQ(ContextUtils.getCurrentActivity(), intent.getData());
                        path = file1.getAbsolutePath();
                    } else if (mOnputFileClip != null && mOnputFileClip.length() > 0
                            && clipPhotoPathCallBack != null) {
                        path = mOnputFileClip.getAbsolutePath();
                    } else {
                        path = "";
                    }

                    if (!TextUtils.isEmpty(path)) {
                        clipPhotoPathCallBack.clipPhotoPathSuccess(path);
                        message = "success";
                    } else {
                        CGError cgError = CGError.FailedToClipPhoto;
                        cgError.setExtra("file is null");
                        if (clipPhotoPathCallBack != null)
                            clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                        message = "error " + cgError.toJsonString();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    CGError cgError = CGError.FailedToClipPhoto;
                    cgError.setExtra(e.getMessage());
                    if (clipPhotoPathCallBack != null)
                        clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                    message = "error " + cgError.toJsonString();
                }
                LogUtil.terminal(new CGNormalReportLog.Builder(LOG_TAG, CGNormalReportLog.CORE_MODULE)
                        .module(CGNormalReportLog.CORE_MODULE).logType(CGLog.LogType.rum)
                        .logLevel(CGLog.LogLevel.e).methodName("CROP_CODE").eTag("CROP_CODE")
                        .eventParams("CROP_CODE: file path = " + (mOnputFileClip == null ? "null" : mOnputFileClip.getAbsolutePath()))
                        .logs("CROP_CODE " + message).build());
                break;
            case ConfigUtils.IMAGE_CAMERA_CODE:
                String messageCamera = "";
                if (mOnputFileCamera != null && mOnputFileCamera.length() > 0) {
                    try {
                        clipPhoto(mOnputFileCamera);
                        messageCamera = "success";
                    } catch (Exception e) {
                        e.printStackTrace();
                        CGError cgError = CGError.FailedToClipPhoto;
                        cgError.setExtra("CAMERA_CODE:" + e.toString());
                        if (clipPhotoPathCallBack != null)
                            clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                        messageCamera = "error:" + cgError.toJsonString();
                    }

                } else {
                    CGError cgError = CGError.FailedToClipPhoto;
                    cgError.setExtra("CAMERA_CODE: file is null");
                    if (clipPhotoPathCallBack != null)
                        clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                    messageCamera = "error:" + cgError.toJsonString();
                }
                LogUtil.terminal(new CGNormalReportLog.Builder(LOG_TAG, CGNormalReportLog.CORE_MODULE)
                        .module(CGNormalReportLog.CORE_MODULE).logType(CGLog.LogType.rum)
                        .logLevel(CGLog.LogLevel.e).methodName("CAMERA_CODE").eTag("CAMERA_CODE")
                        .eventParams("CAMERA_CODE: file path = " + (mOnputFileCamera == null ? "null" : mOnputFileCamera.getAbsolutePath()))
                        .logs("CAMERA_CODE " + messageCamera).build());
                break;
        }
    }

    private void clipPhoto(File file) throws Exception {
        Activity context = ContextUtils.getCurrentActivity();
        String path = getPath(context);
        try {
            if (!TextUtils.isEmpty(path)) {
                mOnputFileClip = new File(path, "clip" + System.currentTimeMillis() + ".png");
                clipPhoto(Uri.fromFile(file), context, mOnputFileClip,
                        aspectX, aspectY, outputX, outputY,
                        ConfigUtils.IMAGE_CROP_CODE);
            } else {
                CGError cgError = CGError.FailedToClipPhoto;
                cgError.setExtra("clipPhoto: des path is null");
                if (clipPhotoPathCallBack != null)
                    clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private String getPath(Activity context) {
        String path = "";
        if (context == null) {
            return path;
        }
        if (Build.VERSION.SDK_INT >= 30) {
            path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        } else {
            path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        }
        File pathF =new File(path);
        if(!pathF.exists()){
            pathF.mkdirs();
        }
        return path;
    }

    @ApiAnnotation(clazz = "CGSDK")
    public void launchPickCrop() {
        String message = "success";
        try {
            if (PermissionUtil.checkPermission(ContextUtils.getCurrentActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                PhotoUtil.openPick(ContextUtils.getCurrentActivity(), ConfigUtils.IMAGE_PICKER_CODE);
            } else {
                CGError cgError = CGError.FailedToClipPhoto;
                cgError.setExtra("IMAGE_PICK: no Permission");
                if (clipPhotoPathCallBack != null)
                    clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
                message = "error:" + cgError.toJsonString();

            }
        } catch (Exception e) {
            e.printStackTrace();
            CGError cgError = CGError.FailedToClipPhoto;
            cgError.setExtra("launchPickCrop: e:" + e.getMessage());
            message = "error:" + cgError.toJsonString();
            if (clipPhotoPathCallBack != null)
                clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
        }
        LogUtil.terminal(new CGNormalReportLog.Builder(LOG_TAG, CGNormalReportLog.CORE_MODULE)
                .module(CGNormalReportLog.CORE_MODULE).logType(CGLog.LogType.rum)
                .logLevel(CGLog.LogLevel.e).methodName("launchPickCrop").eTag("launchPickCrop")
                .eventParams("launchPickCrop: click")
                .logs("launchPickCrop" + message).build());

    }

    @ApiAnnotation(clazz = "CGSDK")
    public void launchCameraCrop() {
        String message = "success";
        try {
            String path = getPath(ContextUtils.getCurrentActivity());
            if (PermissionUtil.checkPermission(ContextUtils.getCurrentActivity(), Manifest.permission.CAMERA)
                    && !TextUtils.isEmpty(path)) {
                mOnputFileCamera = new File(path, "camera" + System.currentTimeMillis() + ".png");
                PhotoUtil.openCamera(ContextUtils.getCurrentActivity(), mOnputFileCamera, ConfigUtils.IMAGE_CAMERA_CODE);
            } else {
                CGError cgError = CGError.FailedToClipPhoto;
                cgError.setExtra("launchCameraCrop: no Permission");
                message = "error:" + cgError.toJsonString();
                if (clipPhotoPathCallBack != null)
                    clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
            }
        } catch (Exception e) {
            e.printStackTrace();
            CGError cgError = CGError.FailedToClipPhoto;
            cgError.setExtra("launchCameraCrop: e:" + e.getMessage());
            message = "error:" + cgError.toJsonString();
            if (clipPhotoPathCallBack != null)
                clipPhotoPathCallBack.clipPhotoPathFailed(cgError);
        }
        LogUtil.terminal(new CGNormalReportLog.Builder(LOG_TAG, CGNormalReportLog.CORE_MODULE)
                .module(CGNormalReportLog.CORE_MODULE).logType(CGLog.LogType.rum)
                .logLevel(CGLog.LogLevel.e).methodName("launchCameraCrop").eTag("launchPickCrop")
                .eventParams("launchCameraCrop: click")
                .logs("launchCameraCrop " + message).build());

    }

    /**
     * 打开图库
     */
    public static void openPick(Activity activity, int req) {
        final Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType(IMAGE_TYPES);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        if (activity != null) {
            activity.startActivityForResult(intent, req);
        }
    }

    /**
     * 打开摄像头
     */
    public static void openCamera(Activity activity, File mOnputFile, int req) {
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        Uri imageUri = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", mOnputFile);
        } else {
            imageUri = Uri.fromFile(mOnputFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        if (activity != null) {
            activity.startActivityForResult(intent, req);
        }
    }

    /**
     * 打开裁剪
     */
    public static void clipPhoto(Uri uri, Activity context, File mOnputFile,
                                 int aspectX, int aspectY, int outputX, int outputY,
                                 int req) throws Exception {
        if (context == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", new File(uri.getPath()));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        if (aspectX > 0) {
            intent.putExtra("aspectX", aspectX);
        }
        if (aspectY > 0) {
            intent.putExtra("aspectY", aspectY);
        }
        if (outputX > 0) {
            intent.putExtra("outputX", outputX);
        }
        if (outputY > 0) {
            intent.putExtra("outputY", outputY);
        }
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//Uri.fromFile(mOnputFile));//FileUtil.getUriForFile(context, mOnputFile)
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + mOnputFile.getAbsolutePath()));//Uri.fromFile(mOnputFile));//FileUtil.getUriForFile(context, mOnputFile)
        }
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true);
        try {
            context.startActivityForResult(intent, req);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}


文件转uri,uri转文件

public class FileUtil {
    /**
     * android 10及以上 uri转file
     */
    @RequiresApi(Build.VERSION_CODES.Q)
    public static File uriToFileApiQ(Context context, Uri uri) throws IOException, NoSuchMethodError {
        File file = null;
        if (uri == null) return file;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            Log.e("File", "clipPhotoPathSuccess SCHEME_FILE:" + uri);
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = "uritofile" + System.currentTimeMillis()
                    + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));
            InputStream is = contentResolver.openInputStream(uri);
            File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
            FileOutputStream fos = new FileOutputStream(cache);
            FileUtils.copy(is, fos);
            file = cache;
            fos.close();
            is.close();

        }
        return file;
    }

    /**
     * Android 10以下
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 获取uri
     *
     * @param context
     * @param file
     * @return
     */
    public static Uri getUriForFile(Context context, File file) {
        Uri fileUri = null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
//                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "clip"+System.currentTimeMillis());
                contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
                fileUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            } else {
                fileUri = Uri.fromFile(file);
            }
//            else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                fileUri = getUriForFile24(context, file);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileUri;
    }

    /**
     * android 7.0以上获取uri的方法
     *
     * @param context
     * @param file
     * @return
     */
    private static Uri getUriForFile24(Context context, File file) {

        Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", file);
        return fileUri;
    }


    public static Uri getUriForContent(Context context, File file) {
        String[] what = new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN,
                MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.MIME_TYPE,
                MediaStore.Images.ImageColumns.DISPLAY_NAME};

        String where = MediaStore.Images.Media.MIME_TYPE + "='image/png'" ;

        Cursor cursor = context.getContentResolver()
                .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        what,
                        where,
                        null,
                        MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
        Uri itemUri = null;
        while (cursor != null && cursor.moveToNext()) {
            int columnId = cursor.getColumnIndex(MediaStore.Images.Media._ID);
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
            if (name.equals(file.getName())) {
                int mediaId = cursor.getInt(columnId);
                itemUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + mediaId);
                return itemUri;
            }

        }
        return itemUri;
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容