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

Android 拍照截圖實作:為什麼拍照一定要走 Uri 而不能用 Bitmap

編輯:關於 Android 程式設計

本文示範如何拍照後進行裁剪。先看效果:

拍照截圖有個先天限制:現在手機鏡頭动辄數百萬畫素,拍出的原始圖非常大。若沿用相冊那套「小圖用 Bitmap 回傳」的做法,極易撞上 TransactionTooLargeException 或 Bundle 大小上限。因此拍照場景不論大小圖,一律用 Uri 操作。

一、準備 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 

二、意圖:呼叫系統相機

使用 MediaStore.ACTION_IMAGE_CAPTURE 就能叫起相機程式,並用 EXTRA_OUTPUT 指定照片寫去哪裡。

 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE 

三、把 Uri 交給裁剪程式

 switch (requestCode) { case TAKE_BIG_PICTURE: Log.d(TAG, "TAKE_BIG_PICTURE: data = " + data);//it seems to be null //TODO sent to crop cropImageUri(imageUri, 800, 400, CROP_BIG_PICTURE); break; case TAKE_SMALL_PICTURE: Log.i(TAG, "TAKE_SMALL_PICTURE: data = " + data); //TODO sent to crop cropImageUri(imageUri, 300, 150, CROP_SMALL_PICTURE); break; default: break; } 

不論大圖小圖,傳的都是 Uri,只有輸出尺寸不同。把共同邏輯抽成一個方法:

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

四、接收裁剪結果

 switch (requestCode) { case CROP_BIG_PICTURE://from crop_big_picture Log.d(TAG, "CROP_BIG_PICTURE: data = " + data);//it seems to be null if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); } break; case CROP_SMALL_PICTURE: if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); }else{ Log.e(TAG, "CROP_SMALL_PICTURE: data = " + data); } break; default: break; } 

兩個實務提醒:一是 com.android.camera.action.CROP 屬於非公開的隱式 Intent,各廠牌實作差異大,記得做版本與機型相容處理;二是別忘了在 Manifest 加上寫入外部儲存的權限,Android 6.0 以上還要動態申請。掌握「一律走 Uri」這個原則,拍照截圖的記憶體風險就能大幅降低。

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