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

Android Bitmap 深入淺出(一):基礎概念篇

編輯:關於 Android 程式設計

做 Android 開發很難不跟圖片打交道,而圖片最麻煩的地方就是吃記憶體,稍不留神就是 OOM。搞清楚 Bitmap 的相關機制、不同 SDK 版本之間的行為差異,以及一些優化手法,對日常開發的幫助非常實際。

這篇先談基礎:像素、儲存位置與載入。

像素

Bitmap 的佔用可以拆成兩塊:像素本身,以及寬、高、顏色型別等描述資訊。像素是記憶體消耗的大頭,而寬高與每個像素的位數則是用來描述圖片的,靠這些資訊就能算出像素佔了多少記憶體。對應到 API 是這幾個:

public final int getWidth()
public final int getHeight()
public final Config getConfig()

Config 是個列舉型別,表示圖片的像素型別,共有 ALPHA_8 (1)、RGB_565 (3)、ARGB_4444 (4)、ARGB_8888 (5) 幾種。也就是說,下面兩種算法結果是相等的:

int b = 1;
switch (bitmap.getConfig()) {
    case ALPHA_8:   b = 1; break;
    case ARGB_4444: b = 2; break;
    case ARGB_8888: b = 4; break;
}
int bytes1 = bitmap.getWidth() * bitmap.getHeight() * b;
int bytes2 = bitmap.getByteCount(); // 需 API 12 以上

但實務上會碰到一個落差:放進 drawable 的圖片,寬高與像素組成明明已知,直接照公式算出來的數字,卻和上面程式碼的結果對不上。原因是 Android 會對圖片做縮放,而縮放比例取決於你把圖片放在了哪個 drawable 目錄。

Android 資源目錄有所謂的 drawable-hdpi、drawable-xhdpi、drawable-xxhdpi,每個目錄對應一個 density。看個用 decodeResource 載入的例子:

BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test4, options);
Log.i(LOGTAG, "options: " + options.inDensity + "," + options.inTargetDensity);

decodeResource 就是 Android 內部載入 Resource 的方式,它最終會走到 decodeResourceStream:

public static Bitmap decodeResourceStream(Resources res, TypedValue value,
        InputStream is, Rect pad, Options opts) {
    if (opts == null) {
        opts = new Options();
    }
    if (opts.inDensity == 0 && value != null) {
        final int density = value.density;
        if (density == TypedValue.DENSITY_DEFAULT) {
            opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
        } else if (density != TypedValue.DENSITY_NONE) {
            opts.inDensity = density;
        }
    }
    if (opts.inTargetDensity == 0 && res != null) {
        opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
    }
    return decodeStream(is, pad, opts);
}

options.inDensity 代表圖片自身的預設像素密度。TypedValue 帶有一個 density,對應圖片來自哪個 drawable 目錄;每個目錄都對應一種螢幕,而螢幕就有 density。TypedValue 的 density 對應 DisplayMetrics 的 densityDpi,densityDpi 表示每英尺的像素數。options.inTargetDensity 則是目前手機螢幕對應的 densityDpi。最終佔用的像素數是:

bytes = 原始圖片寬 × (options.inDensity / options.inTargetDensity)
      × 原始圖片長 × (options.inDensity / options.inTargetDensity)
      × 每個像素點位數

儲存與傳輸

Android 圖片在不同 SDK 版本中存放的位置並不一樣,這段歷史值得記一下。

2.3 及更早版本,圖片像素存在 native 記憶體。Android 的記憶體分為 Java 堆與 native 區,系統會限制每個應用的可用上限,而這個上限是兩者之和。把像素資料放在 native 區有幾個副作用:虛擬機無法自動回收,必須手動呼叫 bitmap.recycle(),很容易造成記憶體洩漏;而且 DDMS 的 monitor 只看得到 Java 堆的變化,新建立一張圖片根本看不出記憶體增加,除錯起來相當不方便。

從 3.0 開始,圖片改放在 Java 堆中,載入新圖片時 monitor 立刻能反映出來,垃圾回收機制也能自動處理。

4.0 之後又有變化:在 Parcel 傳輸時,如果圖片很大,會改用 ashmem 來傳。

到了 6.0,底層已經明顯增加了把圖片存到 ashmem 的介面,儲存策略又是一次調整。

BitmapFactory

BitmapFactory 是負責載入圖片的類別,大致分成三種來源。先把 API 列出來:

public static Bitmap decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, Options opts)
public static Bitmap decodeResource(Resources res, int id, Options opts)
public static Bitmap decodeResource(Resources res, int id)
public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
public static Bitmap decodeByteArray(byte[] data, int offset, int length)
public static Bitmap decodeFile(String pathName, Options opts)
public static Bitmap decodeFile(String pathName)
public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)
public static Bitmap decodeStream(InputStream is)
public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)
public static Bitmap decodeFileDescriptor(FileDescriptor fd)

再往下看它提供的 native 介面:

private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage, Rect padding, Options opts);
private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd, Rect padding, Options opts);
private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts);
private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, int length, Options opts);

分派規則是這樣的:對 File 的 decode 會先轉成 InputStream,走 nativeDecodeStream;對 Resource 的 decode 走 decodeAsset;FileDescriptor 若能轉成 native 的 fd,就走 nativeDecodeFileDescriptor;ByteArray 則直接用 nativeDecodeByteArray。

這裡有個容易踩到的點:對 Resource 做 decode 時,BitmapFactory 會主動設定 Options 的相關參數並進行縮放,所以解出來的圖片尺寸會和原圖不同。 建議花點時間把 BitmapFactory 讀一遍,搞清楚每種方式的差異,才能依場景挑出效率最好的介面。

BitmapFactory.Options

Options 是我們在載入時可以介入的參數。前面已經談過 inDensity 與 inTargetDensity,這裡補上幾個常用的。

inPurgeable

用途是「需要時才載入 Bitmap,不需要時可以回收」。在 4.1 上實測,帶 inPurgeable 載入圖片後記憶體幾乎不 wzrost;不帶的話則會有明顯增加。

inSampleSize

取樣倍率,長與寬都會乘以 1/inSampleSize,用來把圖片縮小載入,避免佔用過大記憶體,很適合做縮圖。

inJustDecodeBounds

設為 true 之後,只用來取得圖片的寬高資訊,不會真正配置像素記憶體:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
// 此時 options.outWidth 與 options.outHeight 就是結果

這篇先談 Bitmap 的基礎資訊、BitmapFactory 與 Options,以及不同版本的儲存差異。後續再往下深入。

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