編輯:Android 資訊
在日常開發中,Bitmap 低頭不見抬頭見,幾乎每個應用都會直接或間接用到它,而背後牽扯的知識點相當密集。本文把 Bitmap 的常用知識做一次系統梳理,涵蓋解碼參數、內存回收、縮放裁剪、矩陣變換、大圖加載與顏色處理等方面。
這裡說的不是方法名與參數的差異,而是解碼後圖片尺寸處理上的關鍵區別:
decodeFile()用於讀取 SD 卡上的圖片,得到的是原始尺寸。
decodeResource()用於讀取 res、raw 等應用內資源,得到的是原始尺寸乘以縮放系數。
可見 decodeResource 多了一個縮放系數,而該系數依賴屏幕密度,並且可以通過 Options 調整:
public class BitmapFactory {
public static class Options {
public boolean inScaled; // 默認 true
public int inDensity; // 無 dpi 文件夾下默認 160
public int inTargetDensity; // 取決於具體屏幕
}
}
現在有一張 720×720 的圖片,我們分幾種情況討論。
設置為 false 時不進行縮放,解碼結果就是 720×720。設置為 true 或不設置時,則根據 inDensity 與 inTargetDensity 計算縮放系數。
把圖片放到不帶 dpi 的 drawable 目錄下:
如果換成 xhdpi 目錄,在 MX4 上解碼後尺寸變為 1080×1080。原因是放入帶 dpi 的目錄會改變 inDensity 的默認值:xhdpi 下為 160 × 2 = 320,於是縮放系數 = 480 / 320 = 1.5,最終得到 1080×1080。
若不希望依賴系統 density,可顯式指定:
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = 1; options.inDensity = 160; options.inTargetDensity = 160; bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.origin, options); // MX4 上 density = 3,但 160 / 160 = 1,解碼結果為 720x720
Android 對 Bitmap 像素數據的內存分配區域在不同版本上有區別:
從 Android 3.0(API 11)開始,Bitmap 的像素數據與 Bitmap 對象一起存放在 Dalvik 堆中。
而在 3.0 之前,像素數據位於 Native 內存。這意味著 3.0 之前 Native 內存的釋放時機不確定,容易引發內存溢出崩潰,官方因此強烈建議在確認不再使用時顯式調用 recycle();3.0 之後則無此要求。
那麼 3.0 之後是否就真的不需要 recycle 了?有觀點認為,既然不需要兼容 Android 2.3,就應該把內存管理完全交給 GC。這個結論值得商榷,其依據是 recycle 方法的註釋:
/**
* This is an advanced call, and normally need not be called,
* since the normal GC process will free up this memory
* when there are no more references to this bitmap.
*/
public void recycle() {}
但這段註釋從 2008 年初始化代碼時就已存在,早期的代碼並沒有因此變得不必要調用 recycle。

如果 3.0 之後真的完全不需要主動回收,最新的 AOSP 源碼應該有所體現。翻閱 SystemUI 與 Gallery2 的代碼,並未發現取締 Bitmap 的 recycle 調用。所以個人看法是:確定不再使用時,recycle 一下並無壞處。至於流傳的某個所謂 bug,本質上是一種極限優化策略,業務代碼中加上對象是否相同的判斷即可規避。
簡單說,內存佔用量取決於三個因素:圖片的像素總數、每個像素的位深(由 Config 決定,ARGB_8888 為 4 字節,RGB_565 為 2 字節),以及是否存在額外的 native 分配。一張 1080×1920 的 ARGB_8888 圖片,僅像素數據就約 8MB。理解這個計算方式,是後續所有優化手段的前提。
BitmapFactory.Options.inBitmap 是 Android 3.0 新增的屬性,設置後可復用既有 Bitmap 的內存塊,從而提升性能並減少 GC 壓力。
但復用是有條件的:Android 4.4 之前只能復用尺寸完全相同的 Bitmap;4.4 之後放寬為「新 Bitmap 不大於可復用 Bitmap」即可。
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) {
// inBitmap 僅對可變 Bitmap 生效,因此強制解碼器返回可變對象
options.inMutable = true;
if (cache != null) {
Bitmap inBitmap = cache.getBitmapFromReusableSet(options);
if (inBitmap != null) {
options.inBitmap = inBitmap;
}
}
}
static boolean canUseForInBitmap(Bitmap candidate, BitmapFactory.Options targetOptions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
int width = targetOptions.outWidth / targetOptions.inSampleSize;
int height = targetOptions.outHeight / targetOptions.inSampleSize;
int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
return byteCount <= candidate.getAllocationByteCount();
}
// 早期版本要求尺寸完全一致,且 inSampleSize 必須為 1
return candidate.getWidth() == targetOptions.outWidth
&& candidate.getHeight() == targetOptions.outHeight
&& targetOptions.inSampleSize == 1;
}
LRU,Least Recently Used,優先丟棄最久未被使用的數據。
與之相對的是 MRU,丟棄最近使用最多的數據。這背後體現的是程序的局部性原理。
實現思路:

LruCache:Android 3.1 與 support v4 中均提供了這一實現,內部基於 LinkedHashMap,所有數據都在內存中。
DiskLruCache:顧名思義是磁盤緩存,實現稍複雜一些。使用它之後不必擔心圖片或文件過多佔滿磁盤,不常用的內容會被自動清理。系統未正式提供,需自行下載引入。
節省內存最有效的手段,是只加載合適尺寸的 Bitmap。以當今相機的像素水準,很多照片都是巨無霸級別,直接全尺寸加載最容易 OOM。正確流程是:先讀取原始寬高,算出合適的縮小倍數,再進行真正的解碼。
public static int calculateSampleSize(BitmapFactory.Options options, int maxWidth, int maxHeight) {
int rawWidth = options.outWidth;
int rawHeight = options.outHeight;
int inSampleSize = 0;
if (rawHeight > maxHeight || rawWidth > maxWidth) {
float ratioWidth = (float) rawWidth / maxWidth;
float ratioHeight = (float) rawHeight / maxHeight;
inSampleSize = (int) Math.min(ratioHeight, ratioWidth);
}
return Math.max(1, inSampleSize);
}
需要特別注意:inSampleSize 只接受 2 的整數次冪。若傳入其他值,系統會向下取最接近的 2 的冪,結果可能與預期不符。
具體做法是先把 inJustDecodeBounds 設為 true,此時 BitmapFactory 只讀取寬高信息寫入 Options,並不真正分配像素內存。拿到尺寸後算出 inSampleSize,再進行第二次真正的解碼。
public static Bitmap decodeThumbnail(String path, int maxWidth, int maxHeight, boolean autoRotate) {
int angle = 0;
if (autoRotate) {
angle = ImageLess.getExifRotateAngle(path);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 此時僅獲取寬高信息,返回的 bitmap 為空
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options, maxWidth, maxHeight);
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inPurgeable = true;
options.inInputShareable = true;
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
bitmap = BitmapFactory.decodeFile(path, options);
if (autoRotate && angle != 0) {
bitmap = rotate(bitmap, angle);
}
return bitmap;
}
這裡的 inPreferredConfig = RGB_565 能直接砍掉一半內存,代價是失去透明通道,適用於不帶alpha的風景照等場景。另外,部分機型的相機照片存在方向標記問題,通過 EXIF 信息自動旋轉校正,能避免用戶看到橫躺的圖片。
系統內建的 ThumbnailUtils 也能生成縮略圖,細節不同但原理一致。
學過線性代數或圖像處理的人都知道 Matrix 的強大:平移、縮放、旋轉、斜切,很多常見變換一行代碼就能搞定,複雜效果也可通過組合實現。每種變換都有 set、pre、post 三個版本,分別代表直接設置、矩陣先乘與矩陣後乘。
旋轉:
Matrix matrix = new Matrix();
matrix.postRotate(angle); // angle 為旋轉角度
Bitmap rotatedBitmap = Bitmap.createBitmap(originBitmap, 0, 0,
originBitmap.getWidth(), originBitmap.getHeight(), matrix, true);
縮放:
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY); // 分別為水平與垂直方向的縮放比例
Bitmap scaledBitmap = Bitmap.createBitmap(originBitmap, 0, 0,
originBitmap.getWidth(), originBitmap.getHeight(), matrix, true);
Bitmap 本身也提供了 createScaledBitmap,本質上同樣基於 Matrix,只是把目標尺寸直接作為參數。不過要注意,強制指定寬高很容易導致圖形變形,實踐中通常保持寬高比縮放更合適。
裁剪的應用場景非常多:頭像剪切、照片裁剪、圓角、圓形等等。
矩形裁剪最簡單,直接用 createBitmap 指定區域:
Bitmap clipBitmap = Bitmap.createBitmap(originBitmap, left, top, clipWidth, clipHeight);
圓角裁剪需要借助 Xfermode。思路是先畫一個圓角矩形作為蒙版,再以 SRC_IN 模式把原圖合成上去,取交集即得結果:
Paint paint = new Paint();
paint.setAntiAlias(true);
Rect rect = new Rect(0, 0, originBitmap.getWidth(), originBitmap.getHeight());
RectF rectF = new RectF(new Rect(0, 0, originBitmap.getWidth(), originBitmap.getHeight()));
Bitmap roundBitmap = Bitmap.createBitmap(originBitmap.getWidth(), originBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(roundBitmap);
// radius 為圓角大小
canvas.drawRoundRect(rectF, radius, radius, paint);
// 關鍵:以 SRC_IN 模式取交集
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(originBitmap, rect, rect, paint);
圓形裁剪原理相同,只是把蒙版換成圓,並需計算居中繪製時的 left 與 top:
int min = originBitmap.getWidth() > originBitmap.getHeight()
? originBitmap.getHeight() : originBitmap.getWidth();
Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap circleBitmap = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(circleBitmap);
canvas.drawCircle(min / 2, min / 2, min / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// 居中顯示
int left = -(originBitmap.getWidth() - min) / 2;
int top = -(originBitmap.getHeight() - min) / 2;
canvas.drawBitmap(originBitmap, left, top, paint);
由此可見,只要更換蒙版形狀,任意多邊形的裁剪都不難實現。
裁剪、濾鏡等功能最終都要落地為文件,否則一切白忙。
public static String save(Bitmap bitmap, Bitmap.CompressFormat format, int quality, File destFile) {
try {
FileOutputStream out = new FileOutputStream(destFile);
if (bitmap.compress(format, quality, out)) {
out.flush();
out.close();
}
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
return destFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
若想更省事地保存到 SD 卡的應用私有目錄下,可以再封裝一層:
public static String save(Bitmap bitmap, Bitmap.CompressFormat format, int quality, Context context) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File dir = new File(Environment.getExternalStorageDirectory()
+ "/" + context.getPackageName() + "/save/");
if (!dir.exists()) {
dir.mkdirs();
}
File destFile = new File(dir, UUID.randomUUID().toString());
return save(bitmap, format, quality, destFile);
}
展示長圖、大圖時,常規做法必然 OOM。系統提供了 BitmapRegionDecoder 來應對這種場景,它可以按矩形區域解碼,只把可見部分載入內存:
public static BitmapRegionDecoder newInstance(String pathName, boolean isShareable) throws IOException { }
public static BitmapRegionDecoder newInstance(InputStream is, boolean isShareable) throws IOException { }
public Bitmap decodeRegion(Rect rect, BitmapFactory.Options options) { }
配合滾動監聽,在 onScroll 中不斷解碼當前可見區域,就能實現順滑的大圖瀏覽。微博的長圖查看正是基於這一思路。
圖像處理是一門深奧的學科,所幸 Android 提供了 ColorMatrix,讓不少簡單特效變得容易。以灰階效果為例:
Bitmap grayBitmap = Bitmap.createBitmap(originBitmap.getWidth(), originBitmap.getHeight(),
Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(grayBitmap);
Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
// 飽和度置 0 即為灰階
colorMatrix.setSaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
canvas.drawBitmap(originBitmap, 0, 0, paint);
除飽和度外,還可以調整對比度、色相旋轉等,通過多個 ColorMatrix 相乘即可疊加多種效果。
既然天天與 Bitmap 打交道,把它徹底理清弄明白是很有必要的。從解碼參數到內存復用,從縮放裁剪到區域加載,這套知識構成了一個完整的閉環:先準確估算內存佔用,再通過降採樣與合適的 Config 把消耗壓到合理水平,最後配合 LRU 緩存與復用策略維持流暢度。
難免仍有遺漏,歡迎補充討論。
深入源碼:Android Handler 消息機制的實現原理
Handler 是 Android 開發中必須掌握的技術,但不少人僅停留在「會用」的階段。使用起來確實很簡單,無非兩步:在主線程重寫 handleMessage() 方法
理解 Android Binder 機制(一):從驅動層看起
Binder 的實作相當複雜,想徹底弄懂並不容易。它橫跨好幾個層次,每一層都有各自的模組與機制要理解。這系列預計分三篇,本文是第一篇:先建立整體架構的骨架,再把主要篇幅留
Android 應用中 Clean 架構的實踐詳解
自從開始開發 Android 應用,我一直覺得自己可以做得更好。我看過不少糟糕的程式碼,其中當然也包括我寫的。Android 系統的複雜性加上劣質的程式碼,勢必釀成災難,
Android 經典側滑菜單 SlidingMenu 使用指南
本文由碼農網 – 小峰原創,轉載請看清文末的轉載要求,歡迎參與我們的付費投稿計劃! SlidingMenu 是一款開源的 Android 類庫,能讓開發者在自己的 App