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 風險。
核心思路:解碼前先讀取圖片尺寸(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.with(context).load(filePath).override(ivWidth, ivHeight).into(imageView);
自動處理縮放、快取、生命週期、OOM 防護,程式碼極度簡潔。