Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 圖片記憶體優化:用 inSampleSize 真正縮小 Bitmap

大圖直接載入是 Android 記憶體溢出(OOM)最常見的來源。很多介面只需要一張縮圖預覽,卻把原始解析度整個解碼進記憶體,等於用 4000 像素寬的資源去塞 200dp 的 ImageView。

要注意的是,在 layout 裡把寬高設小並不會省下任何記憶體——Bitmap 物件本身仍然是原始尺寸,只是被繪製時縮放而已。真正要做的是在解碼階段就降低取樣率,讓 Bitmap 從一開始就是小圖。

核心思路:兩段式解碼

Android 提供 BitmapFactory.Options 上的兩個關鍵欄位:inJustDecodeBounds 只讀取圖片尺寸而不配置像素記憶體;inSampleSize 則指定新圖是原圖的幾分之一。標準做法是先「量尺寸」,再決定縮放倍率,最後才真正解碼。

private Bitmap revitionImageSize(String path, int size) throws IOException {
    // 第一次只取資訊,不分配記憶體
    InputStream temp = this.getAssets().open(path);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(temp, null, options);
    temp.close();

    int i = 0;
    Bitmap bitmap = null;
    while (true) {
        // 寬高都要小於等於目標尺寸
        if ((options.outWidth >> i <= size)
                && (options.outHeight >> i <= size)) {
            // 流必須重新開,不能重用已關閉的舊流
            temp = this.getAssets().open(path);
            options.inSampleSize = (int) Math.pow(2.0D, i);
            // 記得改回 false,否則不會產生任何像素
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeStream(temp, null, options);
            break;
        }
        i += 1;
    }
    return bitmap;
}

幾個容易忽略的細節

  • 位移運算的用意:outWidth >> i 等於寬度除以 2 的 i 次方,而 inSampleSize 只接受 2 的冪次,兩邊用同一個 i 保持一致,才能避免取樣倍數與判斷條件對不上。
  • 務必重新開流:第一次解碼後串流已被消耗並關閉,直接沿用會拿到空內容或拋例外。
  • inJustDecodeBounds 要復位:它維持 true 時 decodeStream 只回傳尺寸、不回傳圖片,回傳值會是 null。
  • 用不到就不再持有:Bitmap 使用完畢應主動 recycle(),並避免在長生命週期物件裡長期 caching 大圖。

除了取樣,也可以搭配 BitmapFactory.Options.inPreferredConfig 選用 RGB_565 降低每像素位元組數,或改用 BitmapRegionDecoder 只解碼需要的區域,都是實務上常見的補充手段。範例原始碼可參考 https://linux.linuxidc.com/ 。

Copyright © Linux教程網 All Rights Reserved