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

Android 使用內建相機擷取圖像並有效管理記憶體

編輯:關於 Android 程式設計

本範例的實作效果是呼叫手機上已安裝的相機來完成拍照,拍好的照片以 ImageView 呈現。

目的在於學習如何呼叫系統相機拍照,並認識大圖處理的技巧,其中主要用到 BitmapFactory 與 BitmapFactory.Options 兩個類別。

載入並顯示一張圖片對記憶體的影響相當顯著。為此,Android 提供了名為 BitmapFactory 的工具類別,它提供了一系列靜態方法,可從各種來源載入 Bitmap。針對本需求,我們從檔案載入圖像並顯示。

BitmapFactory 的可用方法會搭配 BitmapFactory.Options 類別,讓我們能自訂 Bitmap 讀入記憶體的方式。具體而言,載入圖像時可設定 BitmapFactory 應使用的取樣大小:在 Options 中指定 inSampleSize 參數,例如 inSampleSize = 8 時,產生的圖會是原始大小的 1/8。

要注意的是,應先將 BitmapFactoryOptions.inJustDecodeBounds 設為 true,這會通知 BitmapFactory 只回傳圖像的邊界資訊,而不真正解碼圖像本身;取得尺寸資訊後,再將 inJustDecodeBounds 設為 false,進行真正的解碼。

執行效果圖:

原始碼:

activity_main 版面配置:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity 原始碼:

package com.multimediademo1;

import java.io.File;
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.view.Display;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private final static int CAMERA_RESULT = 0;
    private ImageView imageView;
    private String imageFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/myfavoritepicture.jpg";
        File imageFile = new File(imageFilePath);
        Uri imageFileUri = Uri.fromFile(imageFile);
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
        startActivityForResult(intent, CAMERA_RESULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            imageView = (ImageView) findViewById(R.id.imageView);
            Display currentDisplay = getWindowManager().getDefaultDisplay();
            int dw = currentDisplay.getWidth();
            int dh = currentDisplay.getHeight();

            // 先只載入圖像尺寸,而不載入圖像本身
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath, options);
            int heightRatio = (int) Math.ceil(options.outHeight / (float) dh);
            int widthRatio = (int) Math.ceil(options.outWidth / (float) dw);

            // 若兩個比率都大於 1,表示圖像有一條邊大於螢幕
            if (heightRatio > 1 && widthRatio > 1) {
                if (heightRatio > widthRatio) {
                    options.inSampleSize = heightRatio;   // 依高度比率縮放
                } else {
                    options.inSampleSize = widthRatio;
                }
            }
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(imageFilePath, options);
            imageView.setImageBitmap(bitmap);
        }
    }
}

透過 ACTION_IMAGE_CAPTURE 意圖呼叫系統相機,並以 EXTRA_OUTPUT 指定輸出路徑;拍照完成後,利用 inJustDecodeBounds 先讀取尺寸、再依螢幕大小計算 inSampleSize 進行縮放解碼,能有效降低大圖帶來的記憶體負擔,避免 OutOfMemoryError。

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