圖片是 Android App 內存佔用大戶,也是 OOM (OutOfMemoryError) 的高發區。本文系統總結四大優化策略,附帶實戰代碼與避坑指南。
按比例縮小圖片尺寸載入,大幅減少內存佔用。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // 寬高各縮小 1/2,面積 1/4,內存佔用約 1/4
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/large_image.jpg", options);
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
// 使用
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 只解析邊界,不載入像素
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
注意: 不同廠商縮放算法不同,同樣 inSampleSize 在三星、Moto 上畫質差異明顯,需實機測試。
| 配置 | 每像素內存 | 色彩表現 | 適用場景 |
|---|---|---|---|
| ALPHA_8 | 1 byte | 僅透明度 | 遮罩、陰影 |
| RGB_565 | 2 bytes | 無透明通道,65536 色 | 不透明圖片、背景圖 |
| ARGB_4444 | 2 bytes | 4位透明+12位色彩,4096 色 | 簡單透明圖片、舊版兼容 |
| ARGB_8888 | 4 bytes | 完整 32位色彩+透明,1677 萬色 | 默認、高質量圖片 |
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565; // 推薦:節省 50% 內存,無透明損失
// 或
options.inPreferredConfig = Bitmap.Config.ARGB_4444; // 有透明需求但可接受質量下降
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/image.png", options);
避坑: 漸變圖片用 RGB_565/ARGB_4444 會出現色帶(色階明顯),需權衡。
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle(); // 標記 native 內存可回收
bitmap = null; // 斷開 Java 引用
}
核心限制:
setImageBitmap) 嚴禁調用 recycle(),系統仍在使用會 Crash// API 19+ 任意尺寸復用(舊版要求尺寸完全匹配) BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; // 必須可變 options.inBitmap = reusableBitmap; // 復用目標 Bitmap // 解碼新圖片時會嘗試復用 inBitmap 的內存區域 Bitmap newBitmap = BitmapFactory.decodeStream(inputStream, null, options);
Matrix 放大後強制為 ARGB_8888,可通過 copy 轉換:
Matrix matrix = new Matrix();
float scale = 2.0f;
matrix.postScale(scale, scale);
Bitmap scaled = Bitmap.createBitmap(original, 0, 0,
original.getWidth(), original.getHeight(), matrix, true);
// 轉為 RGB_565 節省內存
Bitmap optimized = scaled.copy(Bitmap.Config.RGB_565, false);
// 釋放中間對象
scaled.recycle();
original = null;
public class ImageLoader {
private LruCache memoryCache;
private ExecutorService executor = Executors.newFixedThreadPool(3);
public ImageLoader(Context context) {
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSize = maxMemory / 8; // 1/8 內存作緩存
memoryCache = new LruCache(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024; // KB
}
};
}
public void loadImage(String path, ImageView imageView, int reqWidth, int reqHeight) {
// 1. 內存緩存查找
Bitmap cached = memoryCache.get(path);
if (cached != null) {
imageView.setImageBitmap(cached);
return;
}
// 2. 異步加載
executor.execute(() -> {
Bitmap bitmap = decodeSampledBitmap(path, reqWidth, reqHeight);
if (bitmap != null) {
memoryCache.put(path, bitmap);
new Handler(Looper.getMainLooper()).post(() ->
imageView.setImageBitmap(bitmap));
}
});
}
private Bitmap decodeSampledBitmap(String path, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565; // 默認無透明優先
options.inMutable = true; // 支持 inBitmap 復用
return BitmapFactory.decodeFile(path, options);
}
}
生產環境強烈建議直接使用 Glide/Coil/Picasso,它們已完美封裝以上所有優化:
// Glide 一行代碼包含所有優化
Glide.with(context)
.load(url)
.apply(new RequestOptions()
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(targetWidth, targetHeight)) // 相當於 inSampleSize
.into(imageView);