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

Android 位圖處理入門(一):徹底搞懂 BitmapFactory

編輯:關於 Android 程式設計

只要碰過 Bitmap(位圖),就一定會和 BitmapFactory 打交道。今天我們就把這個類的廬山真面目看清楚。

先看官方定義:

Creates Bitmap objects from various sources, including files, streams, and byte-arrays.

翻譯過來:BitmapFactory 用於從各種資源、檔案、串流與位元組陣列中建立 Bitmap 物件。

換句話說,用這個類就能把圖片資料解碼成 Bitmap(當然建立 Bitmap 還有別的方式,留待下一篇)。它本質上是一個工具類,提供了大量方法,能從不同資料來源解析並產生 Bitmap。

一、BitmapFactory 建立 Bitmap 的方法

1. decodeByteArray(byte[] data, int offset, int length, Options opts)

參數:
  data   存放壓縮圖像資料的位元組陣列
  offset 資料偏移量,決定解碼器從哪裡開始解析
  length 從偏移量起算的位元組數
  opts   可為 null,用來控制取樣率、是否完整解碼,或只回傳尺寸資訊
回傳:
  解碼後的 Bitmap;若資料無法解碼則回傳 null
說明:
  從指定的位元組陣列解出一個不可變的 Bitmap

2. decodeByteArray(byte[] data, int offset, int length)

參數同上,少了 Options 參數
回傳解碼後的 Bitmap,無法解碼時回傳 null

3. decodeFile(String pathName)

參數:
  pathName 要解碼檔案的完整路徑
回傳:
  解碼後的 Bitmap,若路徑為空或無法解碼則回傳 null
說明:
  從檔案解碼產生 Bitmap

4. decodeFile(String pathName, Options opts)

參數:
  pathName 完整路徑
  opts     可為 null,控制取樣與解碼行為,或只要求回傳尺寸
回傳:
  解碼後的 Bitmap,或 null

5. decodeFileDescriptor(FileDescriptor fd)

參數:
  fd 包含待解碼位圖資料的檔案描述符
回傳:
  解碼後的 Bitmap,或 null
說明:
  呼叫結束後描述符的位置不會改變,因此可以再次使用

6. decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)

參數:
  fd         檔案描述符
  outPadding 若非 null,回傳矩形內邊距;若無位圖則設為 (-1,-1,-1,-1)
  opts       可為 null,控制取樣與解碼行為
回傳:
  解碼後的 Bitmap,或 null

7. decodeResource(Resources res, int id, Options opts)

參數:
  res  包含圖像資料的資源物件
  id   圖像資源的 id
  opts 可為 null,控制取樣與解碼行為
回傳:
  解碼後的 Bitmap,或 null
說明:
  與 decodeResourceStream(...) 等價

8. decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, Options opts)

從輸入串流解出一個新 Bitmap。由於拿到了資源資訊,可以進行縮放。

9. decodeResource(Resources res, int id)

參數:
  res 資源物件
  id  資源 id
回傳:
  解碼後的 Bitmap,或 null
說明:
  等同於 Options 傳 null 的 decodeResource 重載

10. decodeResource(Resources res, int id, Options opts)

等同 decodeResourceStream(...),從資源中解出 Bitmap

11. decodeStream(InputStream is, Rect outPadding, Options opts)

參數:
  is         承載原始資料的輸入串流
  outPadding 若非 null,回傳內邊距資訊
  opts       可為 null,控制取樣與解碼行為
回傳:
  解碼後的 Bitmap,或 null
說明:
  串流的位置決定資料從哪裡讀起

12. decodeStream(InputStream is)

從輸入串流解出 Bitmap。若串流為 null 或無法解碼則回傳 null,
串流位置會停在已讀取的編碼資料之後。

以上就是 BitmapFactory 建立 Bitmap 的方法總覽。其中特別值得注意的是 BitmapFactory.Options 這個參數,下面我們來仔細看看它。

二、BitmapFactory.Options 說明與應用

官方定義:

Create a default Options object, which if left unchanged will give the
same result from the decoder as if null were passed.

意思是:建立一個預設的 Options 物件,若不做任何變更,解碼結果與傳入 null 相同。

反過來說,只要妥善設定這個物件,就能更精準地控制 Bitmap 的載入方式。實務上靈活運用,可以顯著降低 OOM(記憶體不足)的發生機率。

2.1 inJustDecodeBounds

If set to true, the decoder will return null (no bitmap), but the out...
fields will still be set, allowing the caller to query the bitmap
without having to allocate the memory for its pixels.

設為 true 時,解碼不會產生 Bitmap,但尺寸等資訊仍會被填入,讓呼叫端可以在不佔用像素記憶體的前提下查詢圖片資訊。

所以,當我們只想取得圖片的寬高時,把 inJustDecodeBounds 設為 true,就能拿到 options.outWidth 與 options.outHeight,而完全不必為像素配置記憶體:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);

int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

補充一點:BitmapFactory 讀到的寬高會受圖片所在位置與裝置影響。同一張圖放在不同的 drawable 目錄,或執行在不同屏幕密度的裝置上,都可能得到不同結果——這與 Android 的資源載入機制有關。

2.2 inSampleSize

取樣率,用來縮放圖片。官方建議取 2 的冪次,例如 1、2、4、8、16。

當 inSampleSize = 1 時,取樣後與原圖等大;設為 2 時,寬高各縮為原圖的 1/2,總像素為 1/4,佔用記憶體也降為 1/4。舉例一張 1024×1024 的圖,若採 ARGB_8888 格式,記憶體約為 1024×1024×4 = 4MB;若 inSampleSize = 2,則降為 512×512×4 = 1MB。若設為小於 1 的值,會按 1 處理;其他值則四捨五入到最接近的 2 的冪次。

實務上我們會動態計算這個值:

public static int calculateInSampleSize(BitmapFactory.Options options,
                                        int reqWidth, int reqHeight) {
    // 圖片的原始高與寬
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // 找出能讓兩邊都大於目標尺寸的、最大的 2 的冪次取樣率
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

可以看到計算結果必然是 2 的冪次。

接著把 inJustDecodeBounds 與 inSampleSize 組合起來使用:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {
    // 第一次先只讀尺寸
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // 計算取樣率
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // 第二次才真正解碼
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

流程很清楚:先只讀邊界取得寬高,算出合適的取樣率,再把 inJustDecodeBounds 設回 false 正式解碼。

例如要載一張圖到大小為 100×100 的 ImageView:

mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

以上幾段範例都取自 Android 官方文件,有時間的話很值得直接讀一遍原文。

三、實際使用 BitmapFactory 建立 Bitmap

先封裝一個簡單的工具類:

/**
 * Bitmap 工具類
 */
public class BitmapUtils {

    public static Bitmap decodeResource(Resources res, int id, BitmapFactory.Options opts) {
        return BitmapFactory.decodeResource(res, id, opts);
    }

    public static Bitmap decodeResource(Resources res, int id) {
        return BitmapFactory.decodeResource(res, id);
    }

    public static Bitmap decodeFile(String pathName) {
        return BitmapFactory.decodeFile(pathName);
    }

    public static Bitmap decodeFile(String pathName, BitmapFactory.Options opts) {
        return BitmapFactory.decodeFile(pathName, opts);
    }

    public static Bitmap decodeStream(InputStream is) {
        return BitmapFactory.decodeStream(is);
    }
}

接著就能從各個來源載入圖片:

// 從 drawable 取得
bitmap = BitmapUtils.decodeResource(getResources(), R.drawable.iv_mt_ic);

// 從 assets 取得
try {
    InputStream is = this.getAssets().open("iv_dzdp_iv.png");
    bitmap = BitmapUtils.decodeStream(is);
} catch (IOException e) {
    e.printStackTrace();
}

// 從 sdcard 取得
String path = "/sdcard/img.jpg";
bitmap = BitmapUtils.decodeFile(path);

總結

實務中直接呼叫 BitmapFactory 建立 Bitmap 的場景相當多,搭配 BitmapFactory.Options 更能做到精準的記憶體控制。本篇就談到這裡,希望對你有幫助;若有描述上的疏漏,也歡迎指正。

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