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

相機實作(二):取得全尺寸照片並以 inSampleSize 正確降採樣

編輯:關於 Android 開發

問題所在

用 ACTION_IMAGE_CAPTURE 拍照後直接把 bitmap 塞進 ImageView,在解析度高的手機上幾乎必然 OOM——一張 1200 萬畫素的照片解碼後要吃掉將近 50MB 記憶體。正確做法分兩步:先只讀取尺寸資訊,再按目標大小降採樣解碼。

版面配置

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

    <Button
        android:id="@+id/take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo" />

    <Button
        android:id="@+id/get_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Photo" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

MainActivity

package com.example.choosepictest;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener {

    static final int REQUEST_IMAGE_CAPTURE = 1;

    private Button takePhoto;
    private Button getPhoto;
    private ImageView picture;
    private Uri imgUri;
    private String mCurrentPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        takePhoto = (Button) findViewById(R.id.take_photo);
        getPhoto = (Button) findViewById(R.id.get_photo);
        picture = (ImageView) findViewById(R.id.picture);

        takePhoto.setOnClickListener(this);
        getPhoto.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.take_photo:
                dispatchTakePictureIntent();
                break;
            default:
                break;
        }
    }

    /** 啟動相機,並指定輸出去處以取得全尺寸照片 */
    private void dispatchTakePictureIntent() {
        File appDir = new File(Environment.getExternalStorageDirectory(), "/etoury/picCache");
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File outputImage = new File(appDir, timeStamp + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mCurrentPhotoPath = outputImage.getAbsolutePath();
        imgUri = Uri.fromFile(outputImage);

        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 關鍵:指定輸出的 Uri,相機就會把完整解析度的照片寫到這裡
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
        }
    }

    /** 降採樣解碼:避免記憶體溢出 */
    private void setPic() {
        int targetW = picture.getWidth();
        int targetH = picture.getHeight();

        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        // 設為 true 時只讀取邊界資訊,不真正解碼、不配置像素記憶體
        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;
        // 恰當的 inSampleSize 能讓 BitmapFactory 配置更少記憶體
        bmOptions.inSampleSize = scaleFactor;
        // 記憶體吃緊時允許回收像素區
        bmOptions.inPurgeable = true;

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE_CAPTURE:
                    galleryAddPic();
                    setPic();
                    break;
                default:
                    break;
            }
        }
    }

    /** 發送掃描通知,讓照片立刻出現在相簿裡 */
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(imgUri);
        this.sendBroadcast(mediaScanIntent);
    }
}

三個容易忽略的細節

inSampleSize 只接受 2 的次方以外的值也能運作,但會向下取整。若 scaleFactor 算出來是 3,實際會用 2;想要精準控制就自己寫 while 迴圈把它湊成 2 的次方。

targetW/targetH 可能為 0。如果在版面尚未量測完成時就呼叫 setPic(),ImageView 的寬高會是 0,導致除零或縮放倍數異常。實務上可用 ViewTreeObserver 或 post() 等到量測完成再解碼。

記得檢查權限與目錄。Android 6.0 之後寫入外部儲存需要動態申請 WRITE_EXTERNAL_STORAGE;Android 10 以上更建議改用 MediaStore 或 app 專屬目錄 getExternalFilesDir(),避免被限定儲存空間政策攔下。

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