編輯:關於 Android 程式設計
本文將以 Android 官方提供的 Sample 範例為依據,踏踏實實地剖析 Bitmap 在使用時的記憶體注意事項。
在深入分析 Bitmap 之前,先簡單認識一下 BitmapFactory 類。BitmapFactory 能依不同的資料來源(檔案、串流、位元組陣列等)建構出 Bitmap 物件。它有一個內部類 BitmapFactory.Options,我們先大致看看其中各參數的作用(未必全部正確):
1. inBitmap:若設定,載入 Bitmap 時會嘗試重用這塊記憶體(記憶體重用),無法重用時會回傳 null,否則回傳 bitmap。
2. inDensity:原始圖片的像素密度。
3. inDither:是否採用抖動解碼。舉個例子理解:若一張色彩豐富的圖,用位數較低的顏色模式解碼,直觀感受就是顏色不夠用,於是在一些漸變區域會出現明顯的斷裂色帶;若採用抖動解碼,就會在這些色帶上以隨機噪聲色填充,讓顯示效果更好、色帶不明顯。
4. inInputShareable:與 inPurgeable 一起使用,若 inPurgeable 為 false 則此設定被忽略;若為 true,它能決定位圖是否共享一個指向資料源的參考,或進行一份拷貝。
5. inJustDecodeBounds:設為 true 時 bitmap 回傳 null,但其他 option 資訊仍會回傳(例如某些情況下我們只想取得圖片寬高,就能把這個參數設為 true)。
6. inMutable:若為 true,解碼方法將始終回傳一個可變的位圖。
7. inPreferQualityOverSpeed:若設為 true,解碼器會嘗試重建影像以獲得更清晰的解碼,甚至不惜犧牲解碼速度,目前僅對 JPEG 有效。
8. inPreferredConfig:若不為空,解碼器會嘗試解碼成這個內部配置;若為空,則嘗試挑選基於系統螢幕的最佳匹配配置。
9. inPremultiplied:預設 true,若設為 true,回傳的 bitmap 帶有 alpha 顏色通道,一般沿用預設即可。
10. inPurgeable:若設為 true,由此產生的位圖會配置其像素,以便系統需要回收記憶體時能將它們清除。
11. inSampleSize:若設定的值大於 1,解碼器會等比縮放圖像以節省記憶體。
12. inScaled:若設為 true,且 inDensity 與 inTargetDensity 不為 0,載入時該位圖會被縮放以匹配 inTargetDensity,而非每次繪製到畫布時依賴圖形系統縮放。
13. inScreenDensity:當前實際使用螢幕的像素密度。
14. inTargetDensity:該位圖將被畫到的目標的像素密度。
15. inTempStorage:解碼時臨時儲存用的,建議設為 16K。
16. mCancel:用於指示已對這個物件呼叫過取消方法的標誌。
17. outHeight:圖像的高度。
18. outMimeType:若知道,這個字串會被設為解碼圖像的 MIME 類型。
19. outWidth:圖像的寬度。
在深入分析 Bitmap 之前,還有一點必須知道:在 Android 3.0 之前,Bitmap 的記憶體配置分為兩部分——一部分配置在 Dalvik 的 VM 堆中,而像素資料的記憶體則配置在 Native 堆中;到了 Android 3.0 之後,Bitmap 的記憶體已全部分配在 VM 堆上。兩者的差別在於:Native 堆的記憶體不受 Dalvik 虛擬機管理,必須手動呼叫 Recycle 方法釋放 Bitmap 的記憶體;而 3.0 之後,我們就能把 Bitmap 的記憶體放心地交給虛擬機管理,只需保證 Bitmap 物件遵守虛擬機的 GC Root Tracing 回收規則即可。
使用 Bitmap 時,主要可從以下幾方面著手優化:
緩存:記憶體緩存+檔案緩存。這嚴格說不算記憶體層面的優化,更貼近效能優化。
及時釋放 Bitmap 的記憶體:正如 aforementioned,Android 3.0 之前有部分記憶體配置在 native 上,必須手動釋放。
複用記憶體:使用 BitmapFactory.Options 的 inBitmap 參數,並把 inMutable 設為 true,搭配 SoftReference 軟參考(記憶體充足時垃圾回收器不會回收它;記憶體不足時才會回收這些軟參考物件的記憶體)。有一點要注意:Android 4.4 以下平台,需保證 inBitmap 與即將 decode 得到的 Bitmap 尺寸規格一致;Android 4.4 及以上平台,只需滿足 inBitmap 的尺寸大於要 decode 的 Bitmap 尺寸規格即可。
降低取樣率:使用 BitmapFactory.Options 的 inSampleSize 參數,从而减少記憶體用量。
接著該進入正題了。
對應上述四個優化點,下面結合 Android 官方 Sample 範例來看看具體怎麼做。對應的範例位於 android-sdk 目錄 /sample/android版本/ui/DisplayingBitmaps。每個優化點在範例中都有體現,分析時會一一指出,為日後使用 Bitmap 提供參照。
在分析範例前,先對幾個類做個大概了解,方便後續程式碼分析。範例的簡單類圖如下:

ImageWorker 類:負責載入圖片,可從記憶體直接載入或異步載入(從磁碟緩存或 processBitmap,取決於 ImageFetcher 類中 processBitmap() 函數的具體實作)。
1. ImageCache 類:緩存的具體實作類。裡面用到兩種緩存——記憶體緩存 LruCache 與檔案緩存 DiskLruCache。緩存圖片時記憶體與檔案都會緩存,但記憶體緩存的優先級高於檔案緩存,會先讀記憶體緩存,再讀檔案緩存。
2. BitmapWorkerTask 類:異步載入(讀檔案緩存或呼叫 processBitmap(),因為這兩種讀取 Bitmap 都耗時)的具體實作。它會先到檔案緩存讀 Bitmap,若沒讀到就呼叫 ImageFetcher 類的 processBitmap() 去載入,再視需要把 Bitmap 加入緩存。
3. ImageResizer 類:依指定大小對 Image 做調整,降低取樣率時會用到。它會依原圖大小與要顯示的大小,按一定演算法算出 inSampleSize 的值(這個計算日後可以直接搬來用)。
4. ImageFetcher 類:從網路下載圖片。processBitmap 在 ImageWorker 中是一個抽象方法,並沒有實作體——因為圖片來源不確定,可能是網路,也可能是本地資料庫,所以 ImageWorker 讓子類依需求做不同實作;在這裡,它做的是從網路讀取圖片。
以上只是大致流程,方便日後使用 Bitmap 時更容易入手。還是按照具體使用流程,直接跳到呼叫處。
ImageGridFragment 類內部類 ImageAdapter 的 getView() 函數中:mImageFetcher.loadImage(Images.imageThumbUrls[position - mNumColumns], imageView)。兩個參數,第一個是 url,第二個是 ImageView。直接跟進去。
ImageWorker 類的 loadImage() 函數:
public void loadImage(Object data, ImageView imageView) { if (data == null) { return; } BitmapDrawable value = null; if (mImageCache != null) { value = mImageCache.getBitmapFromMemCache(String.valueOf(data)); } if (value != null) { // Bitmap found in memory cache imageView.setImageDrawable(value); } else if (cancelPotentialWork(data, imageView)) { final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView); final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task); imageView.setImageDrawable(asyncDrawable); // NOTE: This uses a custom version of AsyncTask that has been pulled from the // framework and slightly modified. Refer to the docs at the top of the class // for more info on what was changed. task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR); } }
第 8–10 行,從記憶體緩存讀圖片資源。
第 12–15 行,記憶體緩存讀到了,直接設定給 ImageView。
第 16–27 行,記憶體緩存裡沒有圖片資源,先呼叫 cancelPotentialWork() 判斷當前 ImageView 對應的 BitmapWorkerTask 是否還在異步請求該 url 的圖像資源:若是則回傳 true,不必重新請求;若不是則回傳 false,此時我們就新建一個 BitmapWorkerTask 去異步請求該圖像資源(可能是檔案緩存,也可能從網路讀,後續分析會體現)。然後透過 AsyncDrawable 把 BitmapWorkerTask 與 ImageView 關聯起來(注意 AsyncDrawable 繼承 BitmapDrawable,所以能 setImageDrawable,正好在 cancelPotentialWork() 函數中會 get 出來做判斷)。
接著就是 BitmapWorkerTask 類的具體實作了,這是重頭戲(注意:前面已透過記憶體緩存讀過,只有在記憶體緩存沒讀到時才會進入 BitmapWorkerTask 異步類)。
那就去看 BitmapWorkerTask 類的 doInBackground() 函數(異步,負責讀檔案緩存、從網路讀圖片資訊)。
@Override protected BitmapDrawable doInBackground(Void... params) { if (BuildConfig.DEBUG) { Log.d(TAG, "doInBackground - starting work"); } final String dataString = String.valueOf(mData); Bitmap bitmap = null; BitmapDrawable drawable = null; // Wait here if work is paused and the task is not cancelled synchronized (mPauseWorkLock) { while (mPauseWork && !isCancelled()) { try { mPauseWorkLock.wait(); } catch (InterruptedException e) {} } } // If the image cache is available and this task has not been cancelled by another // thread and the ImageView that was originally bound to this task is still bound back // to this task and our "exit early" flag is not set then try and fetch the bitmap from // the cache if (mImageCache != null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { bitmap = mImageCache.getBitmapFromDiskCache(dataString); } // If the bitmap was not found in the cache and this task has not been cancelled by // another thread and the ImageView that was originally bound to this task is still // bound back to this task and our "exit early" flag is not set, then call the main // process method (as implemented by a subclass) if (bitmap == null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { bitmap = processBitmap(mData); } // If the bitmap was processed and the image cache is available, then add the processed // bitmap to the cache for future use. Note we don't check if the task was cancelled // here, if it was, and the thread is still running, we may as well add the processed // bitmap to our cache as it might be used again in the future if (bitmap != null) { if (Utils.hasHoneycomb()) { // Running on Honeycomb or newer, so wrap in a standard BitmapDrawable drawable = new BitmapDrawable(mResources, bitmap); } else { // Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable // which will recycle automagically drawable = new RecyclingBitmapDrawable(mResources, bitmap); } if (mImageCache != null) { mImageCache.addBitmapToCache(dataString, drawable); } } if (BuildConfig.DEBUG) { Log.d(TAG, "doInBackground - finished work"); } return drawable; }
第 25–28 行,從檔案緩存讀圖片資源。
第 34–37 行,檔案緩存沒讀到,呼叫 processBitmap() 從網路讀圖片資源,其具體實作在 ImageFetcher 類中,稍後再看。
第 43–56 行,拿到了圖片資源。第 44–47 行,Android 3.0 之後的裝置——如前所述,3.0 之後 Bitmap 記憶體全部分配在 VM 堆上,不需我們手動釋放,這部分照正常流程即可。第 47–51 行,Android 3.0 之前的裝置 Bitmap 有一部分記憶體分配在 Native 堆,需手動釋放,這裡對應 Android 3.0 之前的裝置用了 RecyclingBitmapDrawable——它繼承 BitmapDrawable,並用了兩個計數器 mDisplayRefCount 與 mCacheRefCount。mDisplayRefCount 在 ImageView 顯示時加一、換成顯示別的時先減一;mCacheRefCount 在緩存時加一、從緩存移除時減一。當這個 RecyclingBitmapDrawable 的兩個計數器都為 0 時,代表該資源不再需要,便呼叫 getBitmap().recycle() 釋放。
接著看前面提到的 ImageFetcher 類 processBitmap() 函數。
private Bitmap processBitmap(String data) { if (BuildConfig.DEBUG) { Log.d(TAG, "processBitmap - " + data); } final String key = ImageCache.hashKeyForDisk(data); FileDescriptor fileDescriptor = null; FileInputStream fileInputStream = null; DiskLruCache.Snapshot snapshot; synchronized (mHttpDiskCacheLock) { // Wait for disk cache to initialize while (mHttpDiskCacheStarting) { try { mHttpDiskCacheLock.wait(); } catch (InterruptedException e) {} } if (mHttpDiskCache != null) { try { snapshot = mHttpDiskCache.get(key); if (snapshot == null) { if (BuildConfig.DEBUG) { Log.d(TAG, "processBitmap, not found in http cache, downloading..."); } DiskLruCache.Editor editor = mHttpDiskCache.edit(key); if (editor != null) { if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) { editor.commit(); } else { editor.abort(); } } snapshot = mHttpDiskCache.get(key); } if (snapshot != null) { fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX); fileDescriptor = fileInputStream.getFD(); } } catch (IOException e) { Log.e(TAG, "processBitmap - " + e); } catch (IllegalStateException e) { Log.e(TAG, "processBitmap - " + e); } finally { if (fileDescriptor == null && fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) {} } } } } Bitmap bitmap = null; if (fileDescriptor != null) { bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache()); } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) {} } return bitmap; }
第 10–53 行,透過 mHttpDiskCache 把從網路(downloadUrlToStream)讀到的圖片資源緩存到檔案中,同時取得緩存檔案的描述符 fileDescriptor(此時還不會有記憶體問題,因為網路取得的圖片資源直接放進檔案裡了)。
第 56–59 行,bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache()),準備從檔案讀圖片資訊了,這時就要讀進記憶體,這個函數裡便會對記憶體優化做處理。
decodeSampledBitmapFromDescriptor() 有四個參數:檔案描述符、要顯示的寬度、要顯示的高度、緩存類物件(肯定是在圖片顯示完後要做緩存)。
public static Bitmap decodeSampledBitmapFromDescriptor( FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // If we're running on Honeycomb or newer, try to use inBitmap if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache); } return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); }
第 6 行,options.inJustDecodeBounds 設定為只先解析圖片的寬高資訊,不去載入具體圖片資源。
第 10 行,依 calculateInSampleSize() 函數算出合適的 inSampleSize 值(具體計算可直接看該函數實作,日後要用的話可以直接搬來用)。透過它降低圖片取樣率,等會讀圖片資源時便能大幅減少記憶體消耗。
第 16–18 行,Android 3.0 以上版本,做記憶體複用處理,那就得看看 addInBitmapOptions() 函數了。
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // inBitmap only works with mutable bitmaps so force the decoder to // return mutable bitmaps. options.inMutable = true; if (cache != null) { // Try and find a bitmap to use for inBitmap Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { options.inBitmap = inBitmap; } } }
第 6 行,options.inMutable 設為 true。
第 10 行,到 cache 裡找是否有適合的 Bitmap 可複用,若有就直接賦值給 options.inBitmap。那又得看看怎麼找可複用的 Bitmap 了。
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) { Bitmap bitmap = null; if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) { synchronized (mReusableBitmaps) { final Iterator> iterator = mReusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (null != item && item.isMutable()) { // Check to see it the item can be used for inBitmap if (canUseForInBitmap(item, options)) { bitmap = item; // Remove from reusable set so it can't be used again iterator.remove(); break; } } else { // Remove from the set if the reference has been cleared. iterator.remove(); } } } } return bitmap; }
遍歷 mReusableBitmaps(Bitmap 的軟參考 Set),透過 canUseForInBitmap() 函數判斷是否可複用。判斷規則是:Android 小於 4.4 時需保證寬高都相同且 inSampleSize 為 1;高於 4.4 時,只要要顯示的圖片佔的記憶體比要複用的那個 Bitmap 小即可。
到這裡我們清楚了複用條件的判斷,但還不知道 mReusableBitmaps 這個 set 是什麼時候、在哪裡把可複用的 Bitmap 加進去的。直接看 ImageCache 的 init() 函數,mMemoryCache 初始化部分:
mMemoryCache = new LruCache(mCacheParams.memCacheSize) { /** * Notify the removed entry that is no longer being cached */ @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later mReusableBitmaps.add(new SoftReference(oldValue.getBitmap())); } } }
看到了吧,就是在那裡加進來的。當一個 Bitmap 從記憶體緩存中移除時,這個 Bitmap 對應的記憶體不一定會立刻釋放,我們仍然能用,所以這裡用了軟參考。
至此,整個流程大致分析完了,但感覺還是有點零散。接下來做個總結,看看上面提到的幾個 Bitmap 優化點在範例中是如何落實的。
1. 緩存
範例中,ImageCache 採用了記憶體緩存與檔案緩存的雙緩存機制。
2. 及時釋放 Bitmap 的記憶體(針對 Android 3.0 之前的裝置)
範例中,借助 RecyclingBitmapDrawable 類與 RecyclingImageView 類的配合,實現 Bitmap 記憶體的及時釋放。
RecyclingBitmapDrawable 繼承 BitmapDrawable,裡面有兩個計數器 mDisplayRefCount 與 mCacheRefCount。mDisplayRefCount 在要顯示時加一、換別的顯示時減一;mCacheRefCount 在緩存時加一、從緩存移除時減一。當兩者都為 0 時,代表該資源不再需要,便呼叫 getBitmap().recycle() 釋放。
RecyclingImageView 繼承 ImageView,當它 setImageDrawable 時,會先通知之前的 Drawable 不顯示了,同時通知當前的 Drawable「我要顯示了」——這裡取決於你的 Drawable 對應的是不是 RecyclingBitmapDrawable。
3. 複用記憶體
使用 BitmapFactory.Options 的 inBitmap 參數,並把 inMutable 設為 true,搭配 SoftReference 軟參考(記憶體充足時垃圾回收器不會回收它,記憶體不足時才會回收這些物件的記憶體)。當一個 Bitmap 從記憶體緩存中移除時,就把它加入複用的 Set 集合。判斷是否有 Bitmap 可複用時,先到這個集合拿 Bitmap,再依複用規則判斷(Android 4.4 以下需保證 inBitmap 與即將 decode 的 Bitmap 尺寸規格一致;4.4 及以上只需 inBitmap 尺寸大於要 decode 的 Bitmap 尺寸規格即可)。
4. 降低取樣率
使用 BitmapFactory.Options 的 inSampleSize 參數:先把 options.inJustDecodeBounds 設為 true,只讀取圖片大小;拿到大小後與要顯示的大小做比較,透過 calculateInSampleSize() 函數算出 inSampleSize 的具體值;得到值後,再把 options.inJustDecodeBounds 設為 false 讀圖片資源。
Android與JavaScript的雙向溝通:WebView互動完全解析
手機時代最重要的標誌是什麼?答案無疑是「便利地接入互聯網」。而互聯網最常見的呈現形式就是網頁,網頁裡又幾乎少不了JavaScript。正因如此,Android對JavaS
GLSurfaceView 渲染流程詳解
GLSurfaceView 是 Android 中用於 OpenGL ES 繪圖的重要容器。它不僅負責管理 Surface,還會建立 EGL 環境,並讓渲染工作可以在獨立
Android-Universal-Image-Loader 架構剖析
簡介 Android Universal Image Loader(簡稱 UIL)是一個相當知名的圖片載入框架,專案位址為 https://github.com/nost
開源分享:能即時翻譯英文的 Android 閱讀器
Filter 閱讀器是我近期開發的一款 Android 應用,專為閱讀英文書籍而設計(暫不支援中文,以免亂碼,下一版會改善)。本文將其開源,並講解其中的幾個關鍵技術:TX