萬盛學電腦網

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

Android 圖片內存優化四大核心策略與實戰代碼

前言

圖片是 Android App 內存佔用大戶,也是 OOM (OutOfMemoryError) 的高發區。本文系統總結四大優化策略,附帶實戰代碼與避坑指南。

策略一:縮略圖加載 — inSampleSize

按比例縮小圖片尺寸載入,大幅減少內存佔用。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // 寬高各縮小 1/2,面積 1/4,內存佔用約 1/4
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/large_image.jpg", options);

inSampleSize 計算最佳實踐

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 上畫質差異明顯,需實機測試。

策略二:降低顏色深度 — inPreferredConfig

配置每像素內存色彩表現適用場景
ALPHA_81 byte僅透明度遮罩、陰影
RGB_5652 bytes無透明通道,65536 色不透明圖片、背景圖
ARGB_44442 bytes4位透明+12位色彩,4096 色簡單透明圖片、舊版兼容
ARGB_88884 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 會出現色帶(色階明顯),需權衡。

策略三:及時回收 — recycle() 與 inBitmap 復用

recycle() 使用規範

if (bitmap != null && !bitmap.isRecycled()) {
    bitmap.recycle(); // 標記 native 內存可回收
    bitmap = null;    // 斷開 Java 引用
}

核心限制:

  • 已設置給 View 的 Bitmap (setImageBitmap) 嚴禁調用 recycle(),系統仍在使用會 Crash
  • 被多處引用的 Bitmap 不可輕易 recycle
  • Android 3.0+ 將 Bitmap 像素數據移至 Java 堆,recycle() 效用減弱,更多依賴 GC

inBitmap 復用機制 (API 11+,API 19+ 完善)

// API 19+ 任意尺寸復用(舊版要求尺寸完全匹配)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true; // 必須可變
options.inBitmap = reusableBitmap; // 復用目標 Bitmap
// 解碼新圖片時會嘗試復用 inBitmap 的內存區域
Bitmap newBitmap = BitmapFactory.decodeStream(inputStream, null, options);

策略四:Matrix 放大後修改顏色配置

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,它們已完美封裝以上所有優化:

  • 自動計算 inSampleSize
  • 三級緩存 (內存/磁盤/網絡)
  • 生命週期感知自動取消
  • inBitmap 復用 (Glide 4.0+)
  • WebP/GIF/圖片變換支持
// 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);
copyright © 萬盛學電腦網 all rights reserved