首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Bitmap 縮放至 ImageView 尺寸:高效能最佳實踐

     編輯:程式設計綜合問答

常見錯誤代碼

Bitmap bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), aMatrix, false);
Bitmap.createScaledBitmap(bmp, MyImageview_wt, MyImageview_ht, false); // 回傳值未接收!
MyImageview.setImageBitmap(bmp); // 仍是原圖

問題:createScaledBitmap 回傳**新** Bitmap,原物件不變;且未處理大圖 OOM 風險。

推薦方案:inSampleSize 子採樣載入

核心思路:解碼前先讀取圖片尺寸(inJustDecodeBounds=true),計算縮放比,再以 inSampleSize 載入縮略圖,避免將巨大原圖完整載入記憶體。

完整工具方法

public static Bitmap decodeSampledBitmap(String filePath, int reqWidth, int reqHeight) {
    // 1. 只讀取尺寸
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // 2. 計算 inSampleSize (2 的冪次)
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // 3. 實際解碼
    options.inJustDecodeBounds = false;
    options.inPreferredConfig = Bitmap.Config.RGB_565; // 節省記憶體
    return BitmapFactory.decodeFile(filePath, options);
}

private static int calculateInSampleSize(BitmapFactory.Options options, int reqW, int reqH) {
    int inSampleSize = 1;
    if (options.outHeight > reqH || options.outWidth > reqW) {
        int halfH = options.outHeight / 2;
        int halfW = options.outWidth / 2;
        while ((halfH / inSampleSize) >= reqH && (halfW / inSampleSize) >= reqW) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

使用範例

Bitmap bmp = decodeSampledBitmap(filePath, imageView.getWidth(), imageView.getHeight());
imageView.setImageBitmap(bmp);

進階:Glide / Picasso 圖片載入庫

實務專案建議直接使用成熟庫:

Glide.with(context).load(filePath).override(ivWidth, ivHeight).into(imageView);

自動處理縮放、快取、生命週期、OOM 防護,程式碼極度簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved