代碼:java
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 600); intent.putExtra("outputY", 300); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, CHOOSE_PICTURE);
代碼:android
private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.putExtra("return-data", false); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, requestCode); }
代碼ide
在onActivityResult處理:
this
switch (requestCode) { case CHOOSE_PICTURE: cropImageUri(imageUri, 800, 400, CROP_PICTURE); break; case CROP_PICTURE: if (imageUri != null) { Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); } break; default: break; }
圖片處理代碼:spa
private Bitmap decodeUriAsBitmap(Uri uri) { Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uri)); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } return bitmap; }
SetExtra | DataType | Description |
Crop | String | Signals the crop feature |
aspectX | int | Aspect Ratio |
aspectY | int | Aspect Ratio |
outputX | int | Width of output created from this intent |
outputY | int | Heigh of output created from this intent |
scale | boolean | Should it scale |
Return-data | boolean | Return the bitmap with Action=inline-data by using the data. |
data | Parcelable | Bitmap to process,you may provide it a bitmap. |
circleCrop | String | If this string is not null,it will provide some circular crop. |
MediaStore.EXTRA_OUTPUT(「output」) | URI | set this URi to a File. |
data和MediaStore.EXTRA_OUTPUT都是可選的傳入數據選項,你能夠選擇設置data爲Bitmap,或者將相應的數據與URI關聯起來,你也能夠選擇是否返回數據(return-data: true)。因爲android資源限制,在選擇返回圖片資源時,android會返回一個壓縮處理的小圖(此爲系統控制-大圖容易形成內存溢出),若是想要一個高質量的圖片,能夠如上述代碼中,直接返回uri,根據uri建立須要的圖片。code