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

Android 加載 Bitmap 前先獲取圖片寬高,避免內存溢出

編輯:關於 Android 程式設計

直接 BitmapFactory.decodeFile() 加載一張手機拍出來的大圖,內存瞬間就被吃掉了——一張 800 萬像素的照片按 ARGB_8888 解碼要佔 32MB,在小內存機型上幾乎必然 OOM。

解決思路是「先測尺寸,再按比例解碼」。而 Android 恰好提供了這樣的能力:把 inJustDecodeBounds 設為 true,BitmapFactory 就只讀取文件頭部的尺寸信息,不真正分配像素內存。

一、先只讀邊界,拿到原始尺寸

BitmapFactory.Options options = new BitmapFactory.Options();
/**
 * 關鍵就在這一行:只解析邊界
 * 此時 decodeFile() 返回的 bitmap 為 null,
 * 但 options.outWidth / outHeight 已經被填上了真實尺寸
 */
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/test.jpg", options);
// 此時 bitmap == null,並不是出錯

/**
 * options.outHeight 是原始圖片的高度
 */
Log.e("Test", "Bitmap Height == " + options.outHeight);

這裡最容易被誤解的一點:返回 null 是正常的,不是失敗。真正有價值的結果在 options 對象的 outWidth / outHeight 字段上。

二、封裝成完整的縮略圖加載方法

/**
 * 根據 View(主要是 ImageView)的寬高獲取圖片縮略圖
 *
 * @param path      圖片路徑
 * @param viewWidth 目標寬度
 * @param viewHeight 目標高度
 */
private Bitmap decodeThumbBitmapForFile(String path, int viewWidth, int viewHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();

    // 設置為 true,表示只解析邊界,該對象不佔內存
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // 計算縮放比例
    options.inSampleSize = computeScale(options, viewWidth, viewHeight);

    // 設置為 false,這次才真正把 Bitmap 解析進內存
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
}

/**
 * 計算 Bitmap 的縮放比例,默認不縮放
 */
private int computeScale(BitmapFactory.Options options, int viewWidth, int viewHeight) {
    int inSampleSize = 1;
    if (viewWidth == 0 || viewHeight == 0) {
        return inSampleSize;
    }

    int bitmapWidth = options.outWidth;
    int bitmapHeight = options.outHeight;

    // 若 Bitmap 的寬或高大於目標 View 的寬高,則計算縮放比例
    if (bitmapWidth > viewWidth || bitmapHeight > viewHeight) {
        int widthScale = Math.round((float) bitmapWidth / (float) viewWidth);
        int heightScale = Math.round((float) bitmapHeight / (float) viewHeight);
        // 為了保證圖片不變形,取寬高比例中較小的那個
        inSampleSize = widthScale < heightScale ? widthScale : heightScale;
    }
    return inSampleSize;
}

取兩者中的較小值,是為了保證縮放後的圖仍能完整填滿目標區域(以較大的比例縮小),而不會出現某個方向尺寸不足的情況。

三、inSampleSize 的官方說明

public int inSampleSize

Added in API level 1

If set to a value > 1, requests the decoder to subsample the original image,
returning a smaller image to save memory. The sample size is the number of
pixels in either dimension that correspond to a single pixel in the decoded
bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the
width/height of the original, and 1/16 the number of pixels. Any value <= 1
is treated the same as 1.

Note: the decoder uses a final value based on powers of 2, any other value
will be rounded down to the nearest power of 2.

最後那句話是重點:實際生效的值會被向下取到最近的 2 的冪次。也就是說你傳 5,最終生效的是 4;傳 6,生效的也是 4。所以示例中算出 3 這樣的比例時,並不會精確縮到三分之一,而是按 2 來處理。這個特性決定了 inSampleSize 只能做到「大致合適」,無法精確控制到指定像素尺寸。

四、幾點實踐補充

  • 需要精確尺寸時,配合 inScaled / inDensity / inTargetDensity 或二次創建 Bitmap。用 Bitmap.createScaledBitmap() 可以在解碼後再精確縮一次,代價是多一次內存拷貝。
  • 加上 inPreferredConfig。如果圖片不需要透明通道,把 options.inPreferredConfig = Bitmap.Config.RGB_565 能直接省掉一半內存。
  • Android 4.4 以上可用 inMutable 配合內存複用。設置 inBitmap 複用內存塊,能顯著緩解大量加載時的 GC 壓力,但對尺寸和配置有嚴格要求。
  • 記得回收。不再使用的 Bitmap 及時 recycle(),並在 ImageView 上換圖前把舊圖引用置空,避免殘留引用導致內存無法釋放。

如果不想自己維護這一套細節,Glide、Fresco、Coil 這類圖片庫已經把「按目標尺寸下採樣 + 內存複用 + 生命週期綁定」做到了成熟穩定,業務項目中直接接入通常比自研更划算。

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