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

Android 呼叫系統相機並顯示照片:縮圖與原圖兩種做法

編輯:關於 Android 程式設計

要在自己的 App 裡拍照,最省事的方式是直接呼叫系統相機。但這裡藏著一個很多人栽過的坑:預設拿回來的是縮圖,不是原圖。

做法一:取用 Intent 回傳的縮圖

按下按鈕後啟動相機,拍照完成於 onActivityResult 中從 data 取出 Bitmap:

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);
    }
});

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            Log.v("TestFile", "SD card is not avaiable/writeable right now.");
            return;
        }
        Bundle bundle = data.getExtras();
        Bitmap bitmap = (Bitmap) bundle.get("data");   // 這是縮圖

        FileOutputStream b = null;
        try {
            b = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try { b.flush(); b.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        imageView.setImageBitmap(bitmap);
    }
}

這個 bitmap 的尺寸通常只有幾十 KB,解析度遠低於實際拍攝的畫面。原因是系統相機為了避開跨行程傳輸大 Bitmap 造成 TransactionTooLargeException,只在 extras 裡塞一張符合 View 尺寸的縮圖。適合只需要頭像、縮圖列表的場景。

做法二:指定輸出路徑,拿完整原圖

要取得原始解析度,就必須在啟動相機時告訴它「把檔案寫到哪裡」,而不是透過 Intent 回傳。

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        String name = format.format(new Date());
        fileName = "/sdcard/myImage/" + name + ".jpg";

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileName)));
        startActivityForResult(intent, 1);
    }
});

關鍵就是 MediaStore.EXTRA_OUTPUT 這個 extra。設了它之後,相機 App 會把成品寫到該路徑,回傳的 data 就不再帶 bitmap。

on Activity Result 中只負責驗證檔案並載入顯示:

if (resultCode == Activity.RESULT_OK) {
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        return;
    }
    // 此時檔案已由相機寫入 fileName
    Bitmap bitmap = BitmapFactory.decodeFile(fileName);
    imageView.setImageBitmap(bitmap);
}

版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="拍照" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/btn_camera"
        android:layout_below="@+id/btn_camera"
        android:layout_marginTop="17dp"
        android:background="#999999" />

</RelativeLayout>

這份範例需要修正的地方

原範例在 onCreate 裡用 new File("/sdcard/myImage/").mkdirs() 建目錄,但硬編碼路徑在 Android 4.4 之後就不再可靠。正確作法是呼叫 Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) 取得標準相簿位置,並在 manifest 宣告 WRITE_EXTERNAL_STORAGE;Android 6.0 起還必須在執行期動態申請權限。

其次,Uri.fromFile() 傳給其他 App 會在 Android 7.0 以後觸發 FileUriExposedException。必須改用 FileProvider.getUriForFile() 取得 content:// URI,並在 manifest 中設定對應的 paths 與 grant 權限。

最後,做法二的 on Activity Result 不該再從 extras 取 bitmap,也不該把整張原圖 decode 進記憶體。原圖动辄數 MB,直接 decodeFile 在記憶體受限的裝置上必然 OOM。應改用 BitmapFactory.Options 搭配 inJustDecodeBounds 與 inSampleSize 做降採樣,或使用 ExifInterface 讀取方向資訊後正確旋轉。

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