Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

BitmapFactory.Options 詳解:圖片加載與內存優化實戰

編輯:關於 Android 程式設計

在 Android 裡加載和顯示圖片是一件很吃內存的事,稍不留神就是 OutOfMemoryError。BitmapFactory.Options 給了我們一整套控制手段,可以決定圖片以什麼方式、什麼尺寸讀進內存。先把常用字段梳理清楚,再談實戰。

常用字段速查

字段說明
inSampleSize大於 1 時,解碼器對原圖做抽樣,返回更小的圖以節省內存
inJustDecodeBounds設為 true 時不解碼像素、返回 null,但仍會填充 outWidth/outHeight/outMimeType,供調用方查詢尺寸
inPreferredConfig指定解碼後的位圖配置,如 ARGB_8888、ARGB_4444、RGB_565
inPurgeable允許內存緊張時系統回收位圖像素
inInputShareable與 inPurgeable 配合,允許位圖內容被共享
inDither為 true 時解碼器嘗試對圖像做抖色處理
inScaled/inDensity/inTargetDensity/inScreenDensity控制密度縮放行為,避免系統在繪製時反覆縮放
inMutable為 true 時返回可變位圖
inBitmap嘗試複用該位圖的內存(4.4 起支援)
inPreferQualityOverSpeed寧可犧牲解碼速度也要更高畫質
inTempStorage/mCancel臨時緩衝區與取消標志
outWidth/outHeight/outMimeType解碼結果的寬、高與 MIME 類型

怎麼在不佔內存的前提下拿到圖片尺寸

直覺做法是 BitmapFactory.decodeFile() 得到 Bitmap,再調 getWidth()/getHeight()。但遇到稍大的圖片,這一步就可能直接 OOM。

正確做法是利用 inJustDecodeBounds:設為 true 後,decodeFile 不會真正返回 Bitmap,只把寬高信息回填到 Options 裡,內存開銷幾乎可以忽略。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
// 此時 bmp 為 null,但 options.outWidth / options.outHeight 已是原圖尺寸

按比例生成縮略圖

拿到原始寬高後,可以按目標寬度等比例算出高度。比如在寬度不變形的前提下得到寬為 200 的縮略圖:

int height = options.outHeight * 200 / options.outWidth;
options.outWidth = 200;
options.outHeight = height;
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
image.setImageBitmap(bmp);

不過要注意,這種做法並沒有真正節省內存——解碼時仍然按原圖分配了像素,只是事後得到一個指定尺寸的對象。要從源頭減負,必須用 inSampleSize。

用 inSampleSize 從源頭減負

inSampleSize 的作用是讓解碼器按倍數抽樣。例如設為 4,得到的圖片就是原圖的四分之一尺寸:

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);

這個值可以根據原圖尺寸與目標尺寸推算:

inSampleSize = options.outWidth / 200;

配合以下字段能進一步降低內存峰值:

options.inPreferredConfig = Bitmap.Config.ARGB_4444;  // 默認為 ARGB_8888
options.inPurgeable = true;
options.inInputShareable = true;

更簡潔的寫法是直接指定倍數:

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inSampleSize = 8;
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
imv.setImageBitmap(bmp);   // 圖片變為原來的 1/8

按屏幕尺寸自適應

先只解碼邊界,再拿屏幕寬高與圖片寬高算出比例,取兩者中較大的作為 inSampleSize,最後真正解碼:

Display currentDisplay = getWindowManager().getDefaultDisplay();
int dw = currentDisplay.getWidth();
int dh = currentDisplay.getHeight();

try {
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeStream(
            getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);

    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh);
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw);
    Log.v("HEIGHRATIO", "" + heightRatio);
    Log.v("WIDTHRATIO", "" + widthRatio);

    if (heightRatio > 1 && widthRatio > 1) {
        bmpFactoryOptions.inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
    }
    bmpFactoryOptions.inJustDecodeBounds = false;
    bmp = BitmapFactory.decodeStream(
            getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);

    returnedImageView.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
    Log.v("ERROR", e.toString());
}

完整封裝:通用縮略圖方法

把「兩次解碼」的思路封裝起來,同時限制最小邊長與最大像素數,可以得到一個通用性很強的工具方法:

public static Bitmap createImageThumbnail(String filePath) {
    Bitmap bitmap = null;
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, opts);

    opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128);
    opts.inJustDecodeBounds = false;

    try {
        bitmap = BitmapFactory.decodeFile(filePath, opts);
    } catch (Exception e) {
        // handle exception
    }
    return bitmap;
}

public static int computeSampleSize(BitmapFactory.Options options,
                                    int minSideLength, int maxNumOfPixels) {
    int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
    int roundedSize;
    if (initialSize <= 8) {
        roundedSize = 1;
        while (roundedSize < initialSize) {
            roundedSize <= 1;
        }
    } else {
        roundedSize = (initialSize + 7) / 8 * 8;
    }
    return roundedSize;
}

private static int computeInitialSampleSize(BitmapFactory.Options options,
                                            int minSideLength, int maxNumOfPixels) {
    double w = options.outWidth;
    double h = options.outHeight;
    int lowerBound = (maxNumOfPixels == -1) ? 1
            : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
    int upperBound = (minSideLength == -1) ? 128
            : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));

    if (upperBound < lowerBound) {
        // 兩者無交集時取較大值
        return lowerBound;
    }
    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
        return 1;
    } else if (minSideLength == -1) {
        return lowerBound;
    } else {
        return upperBound;
    }
}

實踐建議

不要把上面所有技巧一股腦堆上去。inPurgeable 與 inInputShareable 從 Android 4.4 起已被標記為冗餘,系統內存管理改進後不再需要;ARGB_4444 的畫質損失明顯,除特殊場景外更推薦 RGB_565(不透明圖)或 ARGB_8888。

真正有效的優化順序是:先用 inJustDecodeBounds 讀尺寸,再用 inSampleSize 降採樣,最後及時 recycle() 並配合 LruCache 做三級緩存。列表場景下,主流做法已經是接入 Glide、Fresco 這類成熟圖片加載庫,它們把採樣、緩存、生命周期綁定、請求取消都處理好了,自研方案的價值主要在於理解原理與應對特殊定製需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved