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;
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容