1、剪裁代码
/** * 图片裁剪,裁剪后存放在沙盒目录下(沙盒目录/picture/子文件夹) * * @param activity activity * @param uri 图片uri * @return 裁剪后的图片uri */ public static void openCrop(Activity activity, Uri uri) { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //未挂在存储设备或者没有读写权限 return; } imgName = System.currentTimeMillis() + ".jpg"; Intent intent = new Intent("com.android.camera.action.CROP"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); intent.setDataAndType(uri, "image/*"); // 设置裁剪 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri); // 图片格式 intent.putExtra("outputFormat", "png"); intent.putExtra("noFaceDetection", true);// 取消人脸识别 intent.putExtra("return-data", true);// true:不返回uri,false:返回uri if (Build.VERSION.SDK_INT >= 30) { //android 11以上,将文件创建在公有目录 String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(); //storage/emulated/0/Pictures File mOnputFile = new File(path, imgName); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + mOnputFile.getAbsolutePath())); } activity.startActivityForResult(intent, REQUEST_CODE_CAPTURE_CROP); }
2、上传代码
/** * @param bmpPath */ public static void uploadImg(Activity activity, String bmpPath, String name) { Log.d(TAG, "uploadImg utils: " + bmpPath + "," + name); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + File.separator + name); Log.d(TAG, "uploadImg file: " + file.getAbsolutePath()); FileUtils.uploadHeadImage(activity, file, Constant.HEAD_URL); } }
3、最为重要的一点 权限的获取
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// 适配android11读写权限
if (Environment.isExternalStorageManager()) {
//已获取android读写权限
} else {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_PERMISSION_CODE);
}
return;
}
具体上传逻辑根据自己需要编写。
其中file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + File.separator + name);很重要