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

Android 相機功能完整指南:拍照、儲存與顯示

編輯:關於 Android 程式設計

要在 App 中整合拍照功能,Android 提供了相當友善的方式——直接啟動系統內建的相機應用即可,不必自己處理複雜的取景與感光元件控制。本文依序說明從權限、拍照、檢視、儲存、加入相簿到記憶體最佳化的完整流程。

一、取得相機權限

先在 AndroidManifest.xml 宣告硬體需求:

<manifest ... >
    <uses-feature android:name="android.hardware.camera" />
    ...
</manifest ... >

若希望沒有相機的裝置也能安裝,可加上 android:required="false",並在執行期以 hasSystemFeature(PackageManager.FEATURE_CAMERA) 判斷,相機不可用時就把拍照功能隱藏起來。

二、啟動拍照

透過 MediaStore.ACTION_IMAGE_CAPTURE 叫起相機:

private void dispatchTakePictureIntent(int actionCode) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(takePictureIntent, actionCode);
}

呼叫前建議先確認裝置有對應的 Activity 可處理這個 Intent:

public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager pm = context.getPackageManager();
    List<ResolveInfo> list = pm.queryIntentActivities(
            new Intent(action), PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

三、檢視縮圖

拍完後,回傳的 Intent 中帶有一張縮圖 Bitmap,可直接顯示在 ImageView:

private void handleSmallCameraPhoto(Intent intent) {
    Bundle extras = intent.getExtras();
    mImageBitmap = (Bitmap) extras.get("data");
    mImageView.setImageBitmap(mImageBitmap);
}

四、儲存全尺寸照片

相機應用預設會把縮圖傳回,若要取得全尺寸照片,必須自己指定儲存位置。Android 2.2 之後可以輕鬆取得公共圖片目錄:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES),
    getAlbumName());

並以時間戳產生檔名,避免覆蓋:

private File createImageFile() throws IOException {
    String timeStamp =
        new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
    File image = File.createTempFile(
        imageFileName, JPEG_FILE_SUFFIX, getAlbumDir());
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

接著把檔案位置透過 Intent 交給相機應用:

File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

五、把照片加入相簿

拍完後主動觸發媒體掃描,讓照片出現在系統相簿中:

private void galleryAddPic() {
    Intent mediaScanIntent =
        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    mediaScanIntent.setData(Uri.fromFile(f));
    this.sendBroadcast(mediaScanIntent);
}

六、解碼時縮小尺寸,節省記憶體

若一次顯示多張照片導致記憶體吃緊,可以在解碼時先讀取尺寸、再按需要縮小,避免直接載入原始大圖造成 OutOfMemoryError:

private void setPic() {
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    // 先只讀尺寸,不載入像素
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // 依縮放比例真正解碼
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    mImageView.setImageBitmap(bitmap);
}

透過以上六個步驟,就能打造一個既完整又省記憶體的拍照流程。其中「先讀尺寸再縮放解碼」的技巧尤其值得牢記,是處理大圖時避免記憶體爆炸的關鍵手法。

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