Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 相冊截圖實作:大圖走 Uri、小圖走 Bitmap 的雙軌策略

編輯:關於 Android 程式設計

本篇接續上一篇對拍照截圖的分析,把場景換成「從相冊選圖並裁剪」。先看成品:

依先前的結論,圖片來源有拍照與相冊兩種,而取回資料的方式則有:

  • 用 Bitmap 直接回傳
  • 用 Uri 傳參、不回傳位圖資料

Bitmap 有大小上限,尺寸一大就可能拿不到實際解析度。因此這裡採用「大圖用 Uri、小圖用 Bitmap」的雙軌做法。

一、先準備 Uri 落點

 private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap 

從相冊選圖的 Action 是 Intent.ACTION_GET_CONTENT。

二、從相冊截大圖

 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_BIG_PICTURE); 

三、從相冊截小圖

 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", 200); intent.putExtra("outputY", 100); intent.putExtra("scale", true); intent.putExtra("return-data", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, CHOOSE_SMALL_PICTURE); 

兩者的差異只在尺寸與 return-data:大圖設為 false,結果寫入 imageUri 指向的檔案;小圖設為 true,直接從 Intent 回傳。

四、在 onActivityResult 分流處理

 switch (requestCode) { case CHOOSE_BIG_PICTURE: Log.d(TAG, "CHOOSE_BIG_PICTURE: data = " + data);//it seems to be null if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri);//decode bitmap imageView.setImageBitmap(bitmap); } break; case CHOOSE_SMALL_PICTURE: if(data != null){ Bitmap bitmap = data.getParcelableExtra("data"); imageView.setImageBitmap(bitmap); }else{ Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data); } break; default: break; } private Bitmap decodeUriAsBitmap(Uri uri){ Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri)); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } return bitmap; } 

要注意的是,各廠牌 ROM 對裁剪 Intent 的支援程度不一,實務上仍需針對主流機型做相容性處理與例外攔截。這套「大圖存 Uri、小圖走 Bundle」的分工,是在記憶體與畫質之間取得平衡的可靠做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved