前提须知:
总所周知,Android11之后存储发生变更,APP只能访问自己的私有目录或者公共目录,不能访问别的app的私有目录。
错误原因:
发生“保存时发生错误,保存失败”这个错误的原因是你调用系统自带的裁剪工具不属于你的app,访问你的app私有目录是不允许的。
解决:
裁切intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)这里的uri使用公用目录:
/**
* 裁剪图片方法实现
*
* @param uri
*/
public void startPhotoZoom(Uri uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//虽然getExternalStoragePublicDirectory方法被淘汰了,但是不影响使用
cropPhoto = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "crop_image.jpg");
} else {
cropPhoto = new File(getExternalCacheDir(), "crop_image.jpg");
}
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setFlags(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 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高 这个值越大清晰度越高,"return-data"这个必须设为false,否则返回的data太大会崩
intent.putExtra("outputX", 600);
intent.putExtra("outputY", 600);
//设置了true的话直接返回bitmap,可能会很占内存
intent.putExtra("return-data", false);
//设置输出的地址
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropPhoto));
//设置输出的格式
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//不启用人脸识别
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, CROP_WITH_DATA);
}