編輯:關於 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 的作用是讓解碼器按倍數抽樣。例如設為 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 這類成熟圖片加載庫,它們把採樣、緩存、生命周期綁定、請求取消都處理好了,自研方案的價值主要在於理解原理與應對特殊定製需求。
手機 MPT 模式和 USB 調試模式有什麼區別?
在手機與電腦的連接方式清單裡,常會看到一個叫 MPT 的選項。它到底是什麼?和開發者熟悉的 USB 調試模式又有何差異? 手機 MPT 模式是什麼? MPT 模式
Android 應用訪問 Linux 驅動的第一步:編寫並測試一個字符設備驅動
一直想找機會親手試一次「用 Android 應用訪問 Linux 內核驅動」,卻總被各種事情耽擱。最近終於騰出時間,下定決心重新試一試。整個嘗試自然要從一個 Linux
Android 實現 HorizontalScrollView 內子控件橫向拖拽排序
網上關於 ListView 上下拖動的例子不少,但項目需要橫向拖拽時,合適的參考卻不多。本文記錄一個在橫向容器中通過長按拖拽、重新排列子控件位置的實現,靠的是 Andro
Fragment 入門談:Android 的創建與生命週期全解析
Fragment 是 Activity 介面中的一部分或一種行為。你可以把多個 Fragment 組合成一個 Activity 來打造多面板介面,也能在不同 Activi