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

Pro Android Media 圖像編程入門(二):擷取並顯示大尺寸圖片

編輯:關於 Android 程式設計

擷取更大的圖像

為了繞開縮圖的尺寸限制,從 Android 1.5 起,我們可以在啟動相機應用的 Intent 中多帶一個 extra。這個 extra 的名稱定義在 MediaStore 類別中,叫做 EXTRA_OUTPUT。它的值(extra 以名稱–值對的形式存在)是一個 URI,用來告訴相機應用拍完的圖要存到哪裡。

下面的程式碼要求相機把圖片存到設備的 SD 卡,檔名為 myfavoritepicture.jpg。

String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
 + "/myfavoritepicture.jpg";
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(i, CAMERA_RESULT);

建立 URI 的部分可以簡化成一行:

imageFileUri = Uri.parse("file:///sdcard/myfavoritepicture.jpg");

不過實務上還是用上面那種寫法比較好——它與設備無關,即使 SD 卡的掛載點命名規則或 URI 語法在不同系統版本上有差異,也仍然能正常運作。

顯示大圖像

載入與顯示圖片很吃記憶體。舉例來說,HTC G1 配備 320 萬像素的相機,拍出的照片通常是 2048×1536 像素。要把這種尺寸的圖以 32 位元色彩載入,需要 2048 × 1536 × 4 ≈ 12,582,912 bytes,大約 13MB 的記憶體。這不見得會立刻讓應用 OOM,但顯然大幅提高了記憶體耗盡的機率。

Android 提供了一個名為 BitmapFactory 的工具類別,裡頭有一系列靜態方法可以從各種來源載入點陣圖。我們要從檔案載入圖片並顯示在最初的 activity 上。所幸 BitmapFactory 的載入方法都接受一個 BitmapFactory.Options 參數,讓我們能控制點陣圖被讀進記憶體的方式。

具體來說,我們可以指定取樣大小。設定 BitmapFactory.Options 的 inSampleSize 參數後,得到的點陣圖會是原圖的 1/inSampleSize。例如把它設為 8,就會產生原圖八分之一大小的圖像。

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inSampleSize = 8;
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
imv.setImageBitmap(bmp);

這是快速載入大圖的做法,但它沒有考慮圖片的原始尺寸與螢幕大小。如果我們能讓圖片縮放到剛好填滿螢幕,那就更理想了。

下面的程式碼示範如何用螢幕尺寸來決定取樣值。採用這種方式後,圖片能盡可能填滿螢幕;若圖片任一維度小於螢幕對應維度,比值會是 0 或小數,這時就不縮放。先取得螢幕維度:

Display currentDisplay = getWindowManager().getDefaultDisplay();
int dw = currentDisplay.getWidth();
int dh = currentDisplay.getHeight();

接著需要知道圖片本身的尺寸,這就要靠 BitmapFactory 幫忙了。把 BitmapFactory.Options.inJustDecodeBounds 設為 true,意思是告訴 BitmapFactory「只要給我尺寸資訊,不要真的解碼圖片」。設成這個模式後,BitmapFactory 會把結果寫進 outHeight 與 outWidth 兩個欄位。

// 只載入圖片的外框尺寸,不載入圖片本身
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)dh);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)dw);
Log.v("HEIGHTRATIO",""+heightRatio);
Log.v("WIDTHRATIO",""+widthRatio);

把圖片的高與寬分別除以螢幕的高與寬,就得到高度比與寬度比;取兩者中較大的那一個作為縮放比值。將這個比值賦給 inSampleSize,就能得到一個載入記憶體後大小接近螢幕的圖像。

// 若兩個比值都大於 1,代表圖片的某一邊大於螢幕
if (heightRatio > 1 && widthRatio > 1) {
 if (heightRatio > widthRatio) {
 // 高度超出較多,以它進行縮小
 bmpFactoryOptions.inSampleSize = heightRatio;
 } else {
 // 寬度超出較多,以它進行縮小
 bmpFactoryOptions.inSampleSize = widthRatio;
 }
}

// 真正解碼圖片
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

下面是「用 Intent 呼叫內建相機,並顯示所得圖片」的完整範例。

package com.apress.proandroidmedia.ch1.sizedcameraintent;
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.util.Log;
import android.view.Display;
import android.widget.ImageView;

public class SizedCameraIntent extends Activity {
 final static int CAMERA_RESULT = 0;
 ImageView imv;
 String imageFilePath;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
 + "/myfavoritepicture.jpg";
 File imageFile = new File(imageFilePath);
 Uri imageFileUri = Uri.fromFile(imageFile);

 Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
 i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
 startActivityForResult(i,CAMERA_RESULT);
 }

 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
 super.onActivityResult(requestCode, resultCode, intent);
 if (resultCode == RESULT_OK) {
 // 取得 ImageView 的參考
 imv = (ImageView) findViewById(R.id.ReturnedImageView);

 Display currentDisplay = getWindowManager().getDefaultDisplay();
 int dw = currentDisplay.getWidth();
 int dh = currentDisplay.getHeight();

 // 只載入圖片的尺寸資訊,不載入圖像本身
 BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
 bmpFactoryOptions.inJustDecodeBounds = true;
 Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

 int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)dh);
 int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)dw);
 Log.v("HEIGHTRATIO",""+heightRatio);
 Log.v("WIDTHRATIO",""+widthRatio);

 // 若兩個比值都大於 1,代表圖片的某一邊大於螢幕
 if (heightRatio > 1 && widthRatio > 1) {
 if (heightRatio > widthRatio) {
 // 高度超出較多,以它進行縮小
 bmpFactoryOptions.inSampleSize = heightRatio;
 } else {
 // 寬度超出較多,以它進行縮小
 bmpFactoryOptions.inSampleSize = widthRatio;
 }
 }

 // 真正解碼圖片
 bmpFactoryOptions.inJustDecodeBounds = false;
 bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

 // 顯示圖片
 imv.setImageBitmap(bmp);
 }
 }
}

上述程式碼需要搭配以下的 layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" >
 <ImageView android:id="@+id/ReturnedImageView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">
 </ImageView>
</LinearLayout>

執行後,返回的满螢幕大小圖片會顯示在 ImageView 中。

實務補充:到了 Android 10(API 29)之後,直接寫 Environment.getExternalStorageDirectory() 存取外部儲存已受強制分區儲存限制,請改用 MediaStore 搭配 ContentResolver.openInputStream();而 Display.getWidth()/getHeight() 也已不建議使用,可改用 WindowMetrics(API 30 起)或 DisplayMetrics 取得可用區域。縮放思路本身仍然適用,只是取尺寸的 API 換了。

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