今天遇見加載大圖片是程序崩潰問題,發現 BitmapFactory.decodeFile 異常,內存溢出。
在網上找到的一些資料與常用的優化辦法,整理記錄下。
感謝以下連接文章中的原作者!
http://chjmars.iteye.com/blog/1157137
http://www.cnblogs.com/hellope/archive/2011/08/23/2150400.html
http://blog.csdn.net/go_to_learn/article/details/9764805
http://blog.sina.com.cn/s/blog_4d6fba1b0100v9az.html
使用android提供的BitmapFactory解碼一張圖片時,有時會遇到該錯誤,即:java.lang.OutOfMemoryError: bitmap size exceeds
VM budget。這往往是由於圖片過大造成的。要想正常使用,一種方式是分配更少的內存空間來存儲,即在載入圖片的時候以犧牲圖片質量爲代價,將圖片進行放縮,這也是不少人現在爲避免以上的OOM所採用的解決方法。但是,這種方法是得不償失的,當我們使用圖片作爲縮略圖查看時候倒是沒有說什麼,但是,當需要提供圖片質量的時候,該怎麼辦呢?java.lang.OutOfMemoryError: bitmap size exceeds VM budget着實讓不少人慾哭無淚呀!前幾天剛好有個需求需要載入SD卡上面的圖片。
一、options.inSampleSize
首先是使用
Bitmap
bmp = BitmapFactory.decodeFile(pePicFile.getAbsolutePath() +
"/"
+info.getImage());
上面參數是我將要讀取的圖片文件及路徑,當文件較小時,程序能夠正常運行,但是當我選擇一張大圖時,程序立刻蹦出了java.lang.OutOfMemoryError:
bitmap size exceeds VM budget的OOM錯誤!
在android設備上(where you have only 16MB memory available),如果使用BitmapFactory解碼一個較大文件,很大的情況下會出現上述情況。那麼,怎麼解決?!
先說之前提到過的一種方法:即將載入的圖片縮小,這種方式以犧牲圖片的質量爲代價。在BitmapFactory中有一個內部類BitmapFactory.Options,其中當options.inSampleSize值>1時,根據文檔:
If
set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. (1 -> decodes full size; 2 -> decodes 1/4th size; 4 -> decode 1/16th size). Because you rarely need to show and have full size bitmap images
on your phone. For manipulations smaller sizes are usually enough.
也就是說,options.inSampleSize是以2的指數的倒數被進行放縮。這樣,我們可以依靠inSampleSize的值的設定將圖片放縮載入,這樣一般情況也就不會出現上述的OOM問題了。現在問題是怎麼確定inSampleSize的值?每張圖片的放縮大小的比例應該是不一樣的!這樣的話就要運行時動態確定。在BitmapFactory.Options中提供了另一個成員inJustDecodeBounds。
1
2
3
|
BitmapFactory.Options
opts = new BitmapFactory.Options(); opts.inJustDecodeBounds
= true ; Bitmap
bitmap = BitmapFactory.decodeFile(imageFile, opts); |
設置inJustDecodeBounds爲true後,decodeFile並不分配空間,但可計算出原始圖片的長度和寬度,即opts.width和opts.height。有了這兩個參數,再通過一定的算法,即可得到一個恰當的inSampleSize。Android提供了一種動態計算的方法。如下:
- /**
- * compute Sample Size
- *
- * @param options
- * @param minSideLength
- * @param maxNumOfPixels
- * @return
- */
- 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;
- }
- /**
- * compute Initial Sample Size
- *
- * @param options
- * @param minSideLength
- * @param maxNumOfPixels
- * @return
- */
- 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 the larger one when there is no overlapping zone.
- return lowerBound;
- }
- if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
- return 1;
- } else if (minSideLength == -1) {
- return lowerBound;
- } else {
- return upperBound;
- }
- }
BitmapFactory.Options
opts = new BitmapFactory.Options(); opts.inJustDecodeBounds
= true ; BitmapFactory.decodeFile(imageFile,
opts); opts.inSampleSize
= computeSampleSize(opts, - 1 , 128 * 128 ); //這裏一定要將其設置回false,因爲之前我們將其設置成了true opts.inJustDecodeBounds
= false ; try { Bitmap
bmp = BitmapFactory.decodeFile(imageFile, opts); imageView.setImageBitmap(bmp); } catch (OutOfMemoryError
err) { } |
- /**
- * get Bitmap
- *
- * @param imgFile
- * @param minSideLength
- * @param maxNumOfPixels
- * @return
- */
- public static Bitmap tryGetBitmap(String imgFile, int minSideLength,
- int maxNumOfPixels) {
- if (imgFile == null || imgFile.length() == 0)
- return null;
- try {
- FileDescriptor fd = new FileInputStream(imgFile).getFD();
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- // BitmapFactory.decodeFile(imgFile, options);
- BitmapFactory.decodeFileDescriptor(fd, null, options);
- options.inSampleSize = computeSampleSize(options, minSideLength,
- maxNumOfPixels);
- try {
- // 這裏一定要將其設置回false,因爲之前我們將其設置成了true
- // 設置inJustDecodeBounds爲true後,decodeFile並不分配空間,即,BitmapFactory解碼出來的Bitmap爲Null,但可計算出原始圖片的長度和寬度
- options.inJustDecodeBounds = false;
- Bitmap bmp = BitmapFactory.decodeFile(imgFile, options);
- return bmp == null ? null : bmp;
- } catch (OutOfMemoryError err) {
- return null;
- }
- } catch (Exception e) {
- return null;
- }
- }
這樣,在BitmapFactory.decodeFile執行處,也就不會報出上面的OOM
Error了。完美解決?如前面提到的,這種方式在一定程度上是以犧牲圖片質量爲代價的。如何才能更加優化的實現需求?
二、BitmapFactory.decodeFileDescriptor
當在android設備中載入較大圖片資源時,可以創建一些臨時空間,將載入的資源載入到臨時空間中。
1
2
|
BitmapFactory.Options
bfOptions= new BitmapFactory.Options(); bfOptions.inTempStorage= new byte [ 12 * 1024 ]; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
BitmapFactory.Options
bfOptions= new BitmapFactory.Options(); bfOptions.inDither= false ;//使圖片不抖動。不是很懂 bfOptions.inPurgeable= true ; //使得內存可以被回收 bfOptions.inTempStorage= new byte [ 12 * 1024 ];//臨時存儲 //
bfOptions.inJustDecodeBounds = true; File
file = new File(pePicFile.getAbsolutePath()
+ "/" +info.getImage()); FileInputStream
fs= null ; try { fs
= new FileInputStream(file); } catch (FileNotFoundException
e) { e.printStackTrace(); } Bitmap
bmp = null ; if (fs
!= null ) try { bmp
= BitmapFactory.decodeFileDescriptor(fs.getFD(), null ,
bfOptions); } catch (IOException
e) { e.printStackTrace(); } finally { if (fs!= null )
{ try { fs.close(); } catch (IOException
e) { e.printStackTrace(); } } } |
當然要將取得圖片進行放縮顯示等處理也可以在以上得到的bmp進行。
PS:請圖片處理後進行內存回收。 bmp.recycle();這樣將圖片佔有的內存資源釋放。
三、BitmapFactory
方法:decodeFileDescriptor()、decodeFile()比較
用decodeFileDescriptor()來生成bimap比decodeFile()省內存
- FileInputStream is = = new FileInputStream(path);
- Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);
- imageView.setImageBitmap(bmp);
查看BitmapFactory的源碼,對比一下兩者的實現,可以發現decodeFile()最終是以流的方式生成bitmap
decodeFile源碼:
- public static Bitmap decodeFile(String pathName, Options opts) {
- Bitmap bm = null;
- InputStream stream = null;
- try {
- stream = new FileInputStream(pathName);
- bm = decodeStream(stream, null, opts);
- } catch (Exception e) {
- /* do nothing.
- If the exception happened on open, bm will be null.
- */
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- // do nothing here
- }
- }
- }
- return bm;
- }
decodeFileDescriptor的源碼,可以找到native本地方法decodeFileDescriptor,通過底層生成bitmap
decodeFileDescriptor源碼:
- public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
- if (nativeIsSeekable(fd)) {
- Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
- if (bm == null && opts != null && opts.inBitmap != null) {
- throw new IllegalArgumentException("Problem decoding into existing bitmap");
- }
- return finishDecode(bm, outPadding, opts);
- } else {
- FileInputStream fis = new FileInputStream(fd);
- try {
- return decodeStream(fis, outPadding, opts);
- } finally {
- try {
- fis.close();
- } catch (Throwable t) {/* ignore */}
- }
- }
- }
- private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,Rect padding, Options opts);
四、補充說明
1,
android系統的手機在系統底層指定了堆內存的上限值,大部分手機的缺省值是16MB,不過也有些高配置的機型是24MB的,所以我們的程序在申請內存空間時,爲了確保能夠成功申請到內存空間,應該保證當前已分配的內存加上當前需要分配的內存值的總大小不能超過當前堆的最大內存值,而且內存管理上將外部內存完全當成了當前堆的一部分,也就是說Bitmap對象通過棧上的引用來指向堆上的Bitmap對象,而堆上的Bitmap對象又對應了一個使用了外部存儲的native圖像,也就是實際上使用的字節數組byte[]來存儲的位圖信息,因此解碼之後的Bitmap的總大小就不能超過8M了。
解決這類問題的最根本的,最有效的辦法就是,使用完bitmap之後,調用bitmap對象的recycle()方法釋放所佔用的內存,以便於下一次使用。
2,
設置系統的最小堆大小
int
newSize = 4 * 1024 * 1024 ; //設置最小堆內存大小爲4MB
VMRuntime.getRuntime().setMinimumHeapSize(newSize);
VMRuntime.getRuntime().setTargetHeapUtilization(0.75); // 設置堆內存的利用率爲75%
堆(HEAP)是VM中佔用內存最多的部分,通常是動態分配的。堆的大小不是一成不變的,當堆內存實際的利用率偏離設定的值的時候,虛擬機會在GC的時候調整堆內存大小,讓實際佔用率向個百分比靠攏。比如初始的HEAP是4M大小,當4M的空間被佔用超過75%的時候,重新分配堆爲8M大;當8M被佔用超過75%,分配堆爲16M大。倒過來,當16M的堆利用不足30%的時候,縮減它的大小爲8M大。重新設置堆的大小,尤其是壓縮,一般會涉及到內存的拷貝,所以變更堆的大小對效率有不良影響。
3,
BitmapFactory?
.Options options = new BitmapFactory? .Options();
options.inTempStorage = new byte[1024*1024*5]; //5MB的臨時存儲空間
Bitmap bm = BitmapFactory? .decodeFile("/mnt/sdcard/a.jpg",options);
補充說明:從創建Bitmap的C++底層代碼BitmapFactory.cpp中的處理邏輯來看,如果option不爲null的話,那麼會優先處理option中設置的各個參數,假設當前你設置option的inTempStorage爲1024*1024*4(4M)大小的話,而且每次解碼圖像時均使用該option對象作爲參數,那麼你的程序極有可能會提前失敗,經過測試,如果使用一張大小爲1.03M的圖片來進行解碼,如果不使用option參數來解碼,可以正常解碼四次,也就是分配了四次內存,而如果使用option的話,就會出現內存溢出錯誤,只能正常解碼兩次。Options類有一個預處理參數,當你傳入options時,並且指定臨時使用內存大小的話,Android將默認先申請你所指定的內存大小,如果申請失敗,就會先拋出內存溢出錯誤。而如果不指定內存大小,系統將會自動計算,如果當前還剩3M空間大小,而解碼只需要2M大小,那麼在缺省情況下將能解碼成功,而在設置inTempStorage大小爲4M的情況下就將出現內存溢出錯誤。所以,通過設置Options的inTempStorage大小也不能從根本上解決大圖像解碼的內存溢出問題。
總之再做android開發時,出現內存溢出是屬於系統底層限制,只要解碼需要的內存超過系統可分配的最大內存值,那麼內存溢出錯誤必然會出現。