萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 圖片加載 OOM 解決方案:BitmapFactory.Options 降採樣、RGB_565、inPurgeable 與三級緩存架構

圖片是 Android App 內存佔用大戶。本文深度解析 BitmapFactory.Options 關鍵參數,提供 降採樣計算、配色格式優化、可清除標誌、三級緩存 (內存/磁盤/網絡) 完整架構,並對比主流圖片庫實現原理。

一、OOM 根因:Bitmap 內存佔用公式

內存 (Bytes) = 寬(px) × 高(px) × BytesPerPixel
// ARGB_8888: 4 bytes/pixel
// RGB_565:   2 bytes/pixel (節省 50%)
-- 例:4000×3000 圖片 ARGB_8888 佔 48MB,超過大多數 App 堆上限

二、BitmapFactory.Options 關鍵參數詳解

參數類型作用建議值
inJustDecodeBoundsboolean僅解析寬高不分配像素內存true (第一次解碼)
inSampleSizeint降採樣倍數 (2 的冪),寬高各縮小 N 倍,像素減少 N² 倍根據目標 View 尺寸計算
inPreferredConfigBitmap.Config解碼配色格式RGB_565 (無透明度需求時)
inPurgeableboolean內存不足時允許系統回收像素數據 (API < 21)true
inInputShareableboolean配合 inPurgeable,標記輸入流可共享true
inMutableboolean生成可變 Bitmap,支援 Canvas 繪製按需

三、完整降採樣加載工具方法

public static Bitmap decodeSampledBitmapFromFile(File file, int reqWidth, int reqHeight) {
    // 1. 獲取原圖尺寸
    BitmapFactory.Options boundsOpts = new BitmapFactory.Options();
    boundsOpts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getAbsolutePath(), boundsOpts);

    // 2. 計算 inSampleSize
    boundsOpts.inSampleSize = calculateInSampleSize(boundsOpts, reqWidth, reqHeight);

    // 3. 正式解碼
    BitmapFactory.Options decodeOpts = new BitmapFactory.Options();
    decodeOpts.inSampleSize = boundsOpts.inSampleSize;
    decodeOpts.inJustDecodeBounds = false;
    decodeOpts.inPreferredConfig = Bitmap.Config.RGB_565;
    decodeOpts.inPurgeable = true;
    decodeOpts.inInputShareable = true;
    // decodeOpts.inBitmap = ... (API 19+ 復用 Bitmap,需同尺寸/配置)

    try {
        return BitmapFactory.decodeFile(file.getAbsolutePath(), decodeOpts);
    } catch (OutOfMemoryError e) {
        // 兜底:再次嘗試更大 inSampleSize
        decodeOpts.inSampleSize *= 2;
        return BitmapFactory.decodeFile(file.getAbsolutePath(), decodeOpts);
    }
}

private static int calculateInSampleSize(BitmapFactory.Options opts, int reqW, int reqH) {
    int inSampleSize = 1;
    if (opts.outHeight > reqH || opts.outWidth > reqW) {
        int halfH = opts.outHeight / 2;
        int halfW = opts.outWidth / 2;
        while ((halfH / inSampleSize) >= reqH && (halfW / inSampleSize) >= reqW) {
            inSampleSize <<= 1; // 乘 2
        }
    }
    return inSampleSize;
}

四、三級緩存架構設計

public class ImageLoader {
    // L1: 內存緩存 (LruCache)
    private final LruCache memoryCache;

    // L2: 磁盤緩存 (DiskLruCache)
    private final DiskLruCache diskCache;

    // L3: 網絡下載 (OkHttp)

    public void loadImage(String url, ImageView target) {
        // 1. 內存查找
        Bitmap bmp = memoryCache.get(url);
        if (bmp != null) { target.setImageBitmap(bmp); return; }

        // 2. 磁盤查找 (IO 線程)
        Executors.newSingleThreadExecutor().execute(() -> {
            Bitmap diskBmp = getFromDiskCache(url);
            if (diskBmp != null) {
                memoryCache.put(url, diskBmp);
                runOnUiThread(() -> target.setImageBitmap(diskBmp));
                return;
            }
            // 3. 網絡下載
            downloadAndCache(url, target);
        });
    }
    // ... 具體實現略
}

五、生產建議:直接使用成熟圖片庫

庫特點適用場景
Glide生命週期感知、GIF 支援、模組化、Kotlin 擴展豐富綜合型 App、列表圖片
CoilKotlin 協程優先、輕量、Compose 原生支援、API 簡潔現代 Kotlin/Compose 專案
FrescoNative 內存 (Ashmem)、WebP/動圖強、大圖分區加載低端機、大圖瀏覽、即時通訊
PicassoAPI 極簡、無生命週期感知、維護較慢簡單靜態圖片展示

手寫加載器僅適合學習原理或極度定製場景,生產環境請直接接入成熟庫,站在巨人肩膀上構建業務。

copyright © 萬盛學電腦網 all rights reserved