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

Android 大圖處理:避免 OOM 的縮圖策略

編輯:關於 Android 程式設計

專案中經常遇到要處理大圖的情況。由於 Android 對每個應用的記憶體有上限,若不先做處理,很容易觸發 OOM。

基本思路

標準做法分三步:

  1. 先只讀取圖片的寬高,不載入像素。
  2. 依據目標 View 的寬高,換算出合適的 inSampleSize。
  3. 用該 inSampleSize 重新解碼,得到縮小後的圖片。

兩個關鍵參數

/**
 * If set to true, the decoder will return null (no bitmap), but
 * the out... fields will still be set, allowing the caller to query
 * the bitmap without having to allocate the memory for its pixels.
 */
public boolean inJustDecodeBounds;

/**
 * If set to a value > 1, requests the decoder to subsample the original
 * image, returning a smaller image to save memory. The sample size is
 * the number of pixels in either dimension that correspond to a single
 * pixel in the decoded bitmap. For example, inSampleSize == 4 returns
 * an image that is 1/4 the width/height of the original, and 1/16 the
 * number of pixels. Any value <= 1 is treated the same as 1.
 * Note: the decoder uses a final value based on powers of 2, any other
 * value will be rounded down to the nearest power of 2.
 */
public int inSampleSize;

inJustDecodeBounds:能在不配置像素記憶體的情況下取得圖片尺寸。
inSampleSize:控制縮小的倍率,且實際生效值會被無條件取捨到最接近的 2 的次方。

開源專案 xUtils、Universal-Image-Loader 與 Foursquare 對大圖的處理思路都類似。

Foursquare 的實作

public class ImageUtils {

    private ImageUtils() { }

    public static void resampleImageAndSaveToNewLocation(String pathInput, String pathOutput)
            throws Exception {
        Bitmap bmp = resampleImage(pathInput, 640);
        OutputStream out = new FileOutputStream(pathOutput);
        bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
    }

    public static Bitmap resampleImage(String path, int maxDim) throws Exception {
        // 第一階段:只取尺寸
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, bfo);

        // 第二階段:依尺寸設定 inSampleSize 後真正解碼
        BitmapFactory.Options optsDownSample = new BitmapFactory.Options();
        optsDownSample.inSampleSize = getClosestResampleSize(bfo.outWidth, bfo.outHeight, maxDim);
        Bitmap bmpt = BitmapFactory.decodeFile(path, optsDownSample);

        Matrix m = new Matrix();
        if (bmpt.getWidth() > maxDim || bmpt.getHeight() > maxDim) {
            BitmapFactory.Options optsScale = getResampling(bmpt.getWidth(), bmpt.getHeight(), maxDim);
            m.postScale((float) optsScale.outWidth / (float) bmpt.getWidth(),
                        (float) optsScale.outHeight / (float) bmpt.getHeight());
        }

        // 依 EXIF 修正拍攝方向
        int sdk = Integer.valueOf(Build.VERSION.SDK).intValue();
        if (sdk > 4) {
            int rotation = ExifUtils.getExifRotation(path);
            if (rotation != 0) {
                m.postRotate(rotation);
            }
        }

        return Bitmap.createBitmap(bmpt, 0, 0, bmpt.getWidth(), bmpt.getHeight(), m, true);
    }

    private static BitmapFactory.Options getResampling(int cx, int cy, int max) {
        float scaleVal;
        if (cx > cy) {
            scaleVal = (float) max / (float) cx;
        } else if (cy > cx) {
            scaleVal = (float) max / (float) cy;
        } else {
            scaleVal = (float) max / (float) cx;
        }
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.outWidth = (int) (cx * scaleVal + 0.5f);
        bfo.outHeight = (int) (cy * scaleVal + 0.5f);
        return bfo;
    }

    private static int getClosestResampleSize(int cx, int cy, int maxDim) {
        int max = Math.max(cx, cy);
        int resample;
        for (resample = 1; resample < Integer.MAX_VALUE; resample++) {
            if (resample * maxDim > max) {
                resample--;
                break;
            }
        }
        return resample > 0 ? resample : 1;
    }

    public static BitmapFactory.Options getBitmapDims(String path) throws Exception {
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, bfo);
        return bfo;
    }
}

一個常見誤解的更正

網路上不少文章主張「不要呼叫 BitmapFactory.decodeResource,因為它最終會透過 Java 層的 createBitmap 完成,會消耗更多記憶體」。

查過 BitmapFactory 的原始碼後可以確認,這個說法並不成立。decodeResource 最終同樣是走 JNI 去取得圖片,並不是在 Java 層多繞一圈。從呼叫時序圖可以清楚看到這條路徑:

補充幾個實務重點

  • inSampleSize 只會取 2 的次方,所以算出 3 實際會用 2,算出 5 實際會用 4。若需要精確尺寸,必須再用 Matrix 做二次縮放。
  • 記得 recycle:不再使用的 Bitmap 應呼叫 recycle() 釋放,並把引用設為 null,協助 GC 盡快回收。
  • 優先使用 RGB_565:不需要透明通道的場景(例如拍照縮圖),用 RGB_565 可比 ARGB_8888 省一半記憶體。
  • EXIF 方向別忽略:手機拍攝的圖片常帶有旋轉資訊,不處理會出現側躺的照片。
  • 搭配快取:縮圖結果應快取起來,避免每次捲動清單都重做一次解碼,Glide、Fresco 這類框架已經把這整套流程封裝好了。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved