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

Android 性能優化之 Bitmap 的記憶體優化

編輯:關於 Android 程式設計

圖片是記憶體消耗的大宗,而 Bitmap 又是最容易失控的一環。本文從 BitmapFactory 的解碼原理談起,說明為什麼同一張圖在不同解析方法下佔用的記憶體會差好幾倍,再給出一套可直接使用的優化工具類與實測數據。

一、BitmapFactory 解析 Bitmap 的原理

BitmapFactory 提供了五個靜態工廠方法:

Bitmap decodeFile(...)
Bitmap decodeResource(...)
Bitmap decodeByteArray(...)
Bitmap decodeStream(...)
Bitmap decodeFileDescriptor(...)

最常用的是 decodeFile、decodeResource、decodeStream 這三個。其中 decodeFile 與 decodeResource 最終都會走到 decodeStream,而 decodeStream 內部再呼叫兩個 native 方法完成實際解析:

nativeDecodeAsset()
nativeDecodeStream()

其他方法(如 decodeByteArray、decodeFileDescriptor)則各有對應的 native 實作。

decodeFile 與 decodeResource 的呼叫路徑差異

decodeFile     → decodeStream
decodeResource → decodeResourceStream → decodeStream

decodeResource 多走了一層 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);
}

這個方法只做了兩件事:

1、為 opts.inDensity 賦值,若未設定則給預設的 160(標準 dpi,此時 1dp = 1px)
2、為 opts.inTargetDensity 賦值,取當前裝置的 densityDpi

參數往下一層傳進 decodeStream,在 native 解析完成後會呼叫這個方法:

private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
    if (outputBitmap == null || opts == null) return;

    final int density = opts.inDensity;
    if (density != 0) {
        outputBitmap.setDensity(density);
        final int targetDensity = opts.inTargetDensity;
        if (targetDensity == 0 || density == targetDensity
                || density == opts.inScreenDensity) {
            return;
        }
        byte[] np = outputBitmap.getNinePatchChunk();
        final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
        if (opts.inScaled || isNinePatch) {
            outputBitmap.setDensity(targetDensity);
        }
    } else if (opts.inBitmap != null) {
        // bitmap 被重用,確保 density 被重設
        outputBitmap.setDensity(Bitmap.getDefaultDensity());
    }
}

中間那段判斷是重點:當 inDensity 與 inTargetDensity(或螢幕 Density)不相等時,就套用 inTargetDensity;相等則沿用 inDensity。

總結:setDensityFromOptions 的效果是把 inTargetDensity 套用到 Bitmap 上,前提是 opts.inScaled == true。

結論

在不設定 Options 的情況下:
1、decodeFile / decodeStream 解析時不會做螢幕適配,得到的是原始尺寸的圖
2、decodeResource 解析時會依當前裝置的 densityDpi 做縮放適配,讓 Bitmap 與螢幕解析度匹配、達到最佳顯示效果,代價是 Bitmap 會比原始檔案更大

這就是為什麼「用 decodeResource 讀一張大圖」經常是 OOM 的兇手——系統貼心地幫你放大了,卻沒人告訴你記憶體也跟著翻倍。

1.1、Density、解析度與 res 目錄的對應關係

DensityDpi解析度res 目錄Density
160dpi320x533mdpi1
240dpi480x800hdpi1.5
320dpi720x1280xhdpi2
480dpi1080x1920xxhdpi3
560dpi1440x2560xxxhdpi3.5

dp 與 px 的換算公式:

px = dp × Density

1.2、densityDpi 與 density 的差別

getResources().getDisplayMetrics().densityDpi —— 螢幕的像素密度
getResources().getDisplayMetrics().density     —— 1dp 等於多少 px

舉例:密度 160 的裝置下 1dp = 1px;密度 320 的裝置下 1dp = 2px。這正是 Android 建議使用 dp 作為布局單位的原因——它能依裝置密度自動換算,不必為每種螢幕各寫一套尺寸。

二、Bitmap 的優化策略

2.1、BitmapFactory.Options 屬性解析

inBitmap               —— 解析時重用指定的 Bitmap,須為等大且 inMutable 為 true
inMutable              —— Bitmap 是否可變(例如要在上面畫線)
inJustDecodeBounds     —— 為 true 時只回傳寬高等屬性,不真正配置像素記憶體
inSampleSize           —— 取樣率,須 >= 1。設為 4 時回傳約為原圖 1/16 大小的 Bitmap
inPreferredConfig      —— Bitmap.Config.ARGB_8888 等
inDither               —— 是否抖動,預設 false
inPremultiplied        —— 預設 true,一般不需更動
inDensity              —— Bitmap 的像素密度
inTargetDensity        —— Bitmap 最終的像素密度
inScreenDensity        —— 當前螢幕的像素密度
inScaled               —— 是否支援縮放,預設 true;開啟時會依 inTargetDensity 縮放
inPurgeable            —— 記憶體不足時,儲存像素的空間是否可被回收
inInputShareable       —— 僅在 inPurgeable 為 true 時生效,是否可共用 InputStream
inPreferQualityOverSpeed —— 為 true 時優先保證畫質而非解碼速度
outWidth               —— 回傳的 Bitmap 寬度
outHeight              —— 回傳的 Bitmap 高度
inTempStorage          —— 解碼暫存空間,建議 16*1024

2.2、七條優化策略

1、慎選 Bitmap.Config(沒有透明需求時用 RGB_565,記憶體直接減半)
2、使用 decodeFile / decodeResource / decodeStream 時設定 inDensity 與 inTargetDensity,兩者應相等,值可取螢幕像素密度 × 0.75f
3、用 inJustDecodeBounds 預先讀取尺寸,再用 inSampleSize 做取樣壓縮
4、對 Density > 240 的裝置做 Bitmap 縮放適配
5、2.3 以上版本善用 inNativeAlloc
6、4.4 以下版本善用 inPurgeable 與 inInputShareable
7、適時回收 Bitmap

2.3、封裝後的解碼工具類

public class BitmapDecodeUtil {

    private static final int DEFAULT_DENSITY = 240;
    private static final float SCALE_FACTOR = 0.75f;
    private static final Bitmap.Config DEFAULT_BITMAP_CONFIG = Bitmap.Config.RGB_565;

    private static BitmapFactory.Options getBitmapOptions(Context context) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = true;
        options.inPreferredConfig = DEFAULT_BITMAP_CONFIG;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;

        // 2.3 以上可透過反射開啟 inNativeAlloc,讓像素記憶體配置在 native 層
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
            try {
                Field field = BitmapFactory.Options.class.getDeclaredField("inNativeAlloc");
                field.setAccessible(true);
                field.setBoolean(options, true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        int displayDensityDpi = context.getResources().getDisplayMetrics().densityDpi;
        float displayDensity = context.getResources().getDisplayMetrics().density;

        // 高解析度裝置(dpi > 240 且 density > 1.5)做額外縮放
        if (displayDensityDpi > DEFAULT_DENSITY && displayDensity > 1.5f) {
            int density = (int) (displayDensityDpi * SCALE_FACTOR);
            options.inDensity = density;
            options.inTargetDensity = density;
        }
        return options;
    }

    /** 直接解碼,不壓縮,但會依螢幕密度自動縮放 */
    public static Bitmap decodeBitmap(Context context, int resId) {
        checkParam(context);
        return BitmapFactory.decodeResource(context.getResources(), resId,
                                            getBitmapOptions(context));
    }

    public static Bitmap decodeBitmap(Context context, String pathName) {
        checkParam(context);
        return BitmapFactory.decodeFile(pathName, getBitmapOptions(context));
    }

    public static Bitmap decodeBitmap(Context context, InputStream is) {
        checkParam(context);
        checkParam(is);
        return BitmapFactory.decodeStream(is, null, getBitmapOptions(context));
    }

    /** 依最大寬高壓縮 */
    public static Bitmap compressBitmap(Context context, int resId,
                                        int maxWidth, int maxHeight) {
        checkParam(context);
        final TypedValue value = new TypedValue();
        InputStream is = null;
        try {
            is = context.getResources().openRawResource(resId, value);
            return compressBitmap(context, is, maxWidth, maxHeight);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
        return null;
    }

    public static Bitmap compressBitmap(Context context, String pathName,
                                        int maxWidth, int maxHeight) {
        checkParam(context);
        InputStream is = null;
        try {
            is = new FileInputStream(pathName);
            return compressBitmap(context, is, maxWidth, maxHeight);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
        return null;
    }

    public static Bitmap compressBitmap(Context context, InputStream is,
                                        int maxWidth, int maxHeight) {
        checkParam(context);
        checkParam(is);

        // 第一趟:只讀尺寸,不配置像素記憶體
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, opt);

        int height = opt.outHeight;
        int width  = opt.outWidth;
        int sampleSize = computeSampleSize(width, height, maxWidth, maxHeight);

        // 第二趟:帶著 inSampleSize 真正解碼
        BitmapFactory.Options options = getBitmapOptions(context);
        options.inSampleSize = sampleSize;
        return BitmapFactory.decodeStream(is, null, options);
    }

    private static int computeSampleSize(int width, int height,
                                         int maxWidth, int maxHeight) {
        int inSampleSize = 1;
        if (height > maxHeight || width > maxWidth) {
            final int heightRate = Math.round((float) height / (float) maxHeight);
            final int widthRate  = Math.round((float) width / (float) maxWidth);
            inSampleSize = heightRate < widthRate ? heightRate : widthRate;
        }
        // inSampleSize 建議取 2 的冪次,這裡簡化為去掉尾數的奇數
        if (inSampleSize % 2 != 0) {
            inSampleSize -= 1;
        }
        return inSampleSize <= 1 ? 1 : inSampleSize;
    }

    private static <T> void checkParam(T param) {
        if (param == null) throw new NullPointerException();
    }
}

工具類提供兩類方法:
一、decodeBitmap:不做尺寸壓縮,但會依螢幕密度自動縮放。
二、compressBitmap:先讀尺寸算出 inSampleSize 再解碼,同時也會依密度縮放。

這裡有個細節值得注意:compressBitmap 之所以能只解碼兩次就完成,全靠 inJustDecodeBounds。第一趟不配置像素記憶體、只取寬高,開銷極小;第二趟才帶著 inSampleSize 做真正的解碼。這是 Android 圖片載入最經典的取樣技巧。

三、優化前後的效能對比

測試圖片大小 3.26M、解析度 2048×2048,分別在兩台不同密度的裝置上比較:

3.1、density 為 320 的裝置

3.2、density 為 560 的裝置

從數據可以清楚看到:載入同一張圖,螢幕像素密度越高的裝置,所需記憶體越大,而且解碼出來的 Bitmap 寬高也會隨密度改變。這正好印證了前面的分析——decodeResource 會自動適配當前裝置解析度,而其他解碼方法不會。

依照這個思路,工具類在每個方法中都加入了依螢幕密度自動適配的邏輯。而實務上大多數場景並不需要那麼高的清晰度,因此可以更進一步:在 240 < density ≤ 400 時乘以 0.8,density > 400 時乘以 0.7。對照上面兩張圖中 bitmap 與 decodeBitmap 兩列的數值可以看到,decodeBitmap 只是對 density 做了些許縮放,佔用記憶體卻大幅下降,而顯示效果與原本幾乎無差別。

接著是 inSampleSize 壓縮的結果:壓縮後的視覺差異同樣不明顯,記憶體節省卻相當可觀。這說明在圖片優化上,「憑感覺調高畫質」往往是純粹的浪費。

四、Bitmap 的回收

4.1、Android 2.3.3(API 10)及以下

在 2.3 以下的系統中,Bitmap 的像素資料存放在 native 記憶體,而 Bitmap 物件本身存放在 Java 堆。因此回收時必須處理兩邊:

先呼叫 recycle() 釋放 native 中的像素資料,再把 Bitmap 物件參照設為 null,讓 GC 能回收 Java 堆中的物件。

4.2、Android 3.0(API 11)及以上

3.0 之後,像素資料與物件本身都位於 Java 堆,由 GC 統一管理。此時不需要主動呼叫 recycle(),只要把參照設為 null 即可。

反過來說,在 3.0 以上刻意呼叫 recycle() 反而有害——如果該 Bitmap 仍被其他 UI 元件引用(例如 ImageView 尚未釋放),後續繪製時就會直接拋出 Canvas: trying to use a recycled bitmap 的錯誤。這是升級專案時很常見的崩潰來源。

五、實務總結

把整篇濃縮成一份可執行的清單:

1. 一律先讀尺寸再解碼。用 inJustDecodeBounds = true 取寬高,算出 inSampleSize 後再真正解碼,這是成本最低、效果最明顯的一步。

2. 沒有透明需求就用 RGB_565。相比 ARGB_8888,每個像素從 4 位元組降到 2 位元組,記憶體直接減半。

3. 依螢幕密度做縮放。高 dpi 裝置上 decodeResource 的自動放大往往是記憶體爆掉的主因,明確設定 inDensity / inTargetDensity 把主導權拿回來。

4. 搭配成熟框架。Glide、Fresco 這類圖片庫已經把取樣、快取、生命週期管理、記憶體複用(inBitmap)全部處理好了。除非有特殊需求,自研載入邏輯的成本通常高於收益。

5. 別忘了 recycle 的版本差異。2.3 以下必須 recycle + 置 null;3.0 以上交給 GC 就好,多此一舉反而危險。

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