APP 中選取圖片之后,有時候需要進行剪裁,比如頭像。
以下是啟動代碼。
在我的項目中,傳的是 filePath,所以我轉了一下,但實際上從相冊選擇圖片后,用 data.getData() 就可獲得 uri。Uri uri = Uri.fromFile(new File(filePath));
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(, "image/*");
intent.putExtra("crop", "true"); // 可剪裁
intent.putExtra("aspectX", 10); // 高比例
intent.putExtra("aspectY", 10); // 寬比例
intent.putExtra("outputX", size); // 寬尺寸
intent.putExtra("outputY", size); // 高尺寸
intent.putExtra("scale", true); // 保持比例
intent.putExtra("return-data", true); // 剪裁后,是否返回 Bitmap
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // 輸出 JPEG
intent.putExtra("noFaceDetection", false); // 人臉識別,開啟后,探測到人臉后會將剪裁框移到人臉上
activity.startActivityForResult(intent, 123456); // 啟動
以下是剪裁后的處理:@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 123456 && resultCode == RESULT_OK) {
// 用戶頭像剪裁后
Bitmap bitmap = data.getExtras().getParcelable("data");
// 演示保存到緩存中
// 目錄
String cacheDirectoryPath = getCacheDir().getPath();
File dir = new File(cacheDirectoryPath);
if (!dir.exists()) {
dir.mkdirs(); // 目錄不存在就創建
}
// 文件保存
String filePath = cacheDirectoryPath + File.separator + "cutted.jpg";
File file = new File(filePath);
try {
FileOutputStream fos = new FileOutputStream(file);
//通過io流的方式來壓縮保存圖片
bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:由于安卓的亂象,啟動剪裁時,某些手機中會報 ActivityNotFound 的異常。