圖片是 Android App 內存佔用大戶。本文深度解析 BitmapFactory.Options 關鍵參數,提供 降採樣計算、配色格式優化、可清除標誌、三級緩存 (內存/磁盤/網絡) 完整架構,並對比主流圖片庫實現原理。
內存 (Bytes) = 寬(px) × 高(px) × BytesPerPixel
// ARGB_8888: 4 bytes/pixel
// RGB_565: 2 bytes/pixel (節省 50%)
-- 例:4000×3000 圖片 ARGB_8888 佔 48MB,超過大多數 App 堆上限
| 參數 | 類型 | 作用 | 建議值 |
|---|---|---|---|
inJustDecodeBounds | boolean | 僅解析寬高不分配像素內存 | true (第一次解碼) |
inSampleSize | int | 降採樣倍數 (2 的冪),寬高各縮小 N 倍,像素減少 N² 倍 | 根據目標 View 尺寸計算 |
inPreferredConfig | Bitmap.Config | 解碼配色格式 | RGB_565 (無透明度需求時) |
inPurgeable | boolean | 內存不足時允許系統回收像素數據 (API < 21) | true |
inInputShareable | boolean | 配合 inPurgeable,標記輸入流可共享 | true |
inMutable | boolean | 生成可變 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、列表圖片 |
| Coil | Kotlin 協程優先、輕量、Compose 原生支援、API 簡潔 | 現代 Kotlin/Compose 專案 |
| Fresco | Native 內存 (Ashmem)、WebP/動圖強、大圖分區加載 | 低端機、大圖瀏覽、即時通訊 |
| Picasso | API 極簡、無生命週期感知、維護較慢 | 簡單靜態圖片展示 |
手寫加載器僅適合學習原理或極度定製場景,生產環境請直接接入成熟庫,站在巨人肩膀上構建業務。