圖片解碼後佔用記憶體 = 寬 × 高 × 字節/像素 (ARGB_8888 = 4 bytes)。一張 4000x3000 圖約 48MB,輕易超過 App 記憶體上限 (通常 128~512MB)。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 只讀取尺寸,不載入像素
BitmapFactory.decodeResource(getResources(), R.drawable.large_image, options);
int sampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize; // 2 的冪次:1,2,4,8...
options.inPreferredConfig = Bitmap.Config.RGB_565; // 2 bytes/px,省一半記憶體
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.large_image, options);
public 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 *= 2;
}
}
return inSampleSize;
}
InputStream is = context.getResources().openRawResource(R.drawable.large_image); // 放在 res/raw 避免系統預解碼
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inPurgeable = true; // API 21 棄用,但舊版允許系統在記憶體緊張時回收像素
options.inInputShareable = true; // 配合 inPurgeable
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
decodeStream 經 JNI 直接解碼到 Native 記憶體,減少 Java Heap 壓力。options.inMutable = true;
options.inBitmap = reusableBitmap; // 來自 LruCache 或自行管理的可複用 Bitmap 池
// 要求:reusableBitmap 尺寸 >= 目標尺寸、配色格式相容
Bitmap bitmap = BitmapFactory.decodeResource(res, id, options);
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle(); // 釋放 Native 記憶體 (API 11+ 自動回收 Java 端對象)
bitmap = null;
}
System.gc(); // 僅建議,不保證立即執行
<application android:largeHeap="true" ... >
或程式碼動態設定 (需簽名權限/系統簽名):
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f); // 目標堆使用率
VMRuntime.getRuntime().setMinimumHeapSize(6 * 1024 * 1024); // 最小 6MB
Glide.with(this).load(url).override(800,600).into(imageView);| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| inSampleSize | 縮略圖、列表圖 | 簡單、官方 API | 需計算尺寸、RGB_565 畫質稍失真 |
| decodeStream + Raw | 大圖、不想被系統預解碼 | 繞過 Java 拷貝 | 需自適配密度、Raw 資源打包增大 APK |
| inBitmap 復用 | 頻繁替換大圖 (相簿、編輯器) | 極大減少 GC、避免 OOM | API 19+、管理複雜、尺寸格式需匹配 |
| 圖片庫 | 99% 一般應用 | 全自動、最佳實踐內建 | 增加依賴體積 |