android BitmapFactory的內存溢出

  今天遇見加載大圖片是程序崩潰問題,發現 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提供了一種動態計算的方法。如下:

  1. /** 
  2.  * compute Sample Size 
  3.  *  
  4.  * @param options 
  5.  * @param minSideLength 
  6.  * @param maxNumOfPixels 
  7.  * @return 
  8.  */  
  9. public static int computeSampleSize(BitmapFactory.Options options,  
  10.         int minSideLength, int maxNumOfPixels) {  
  11.     int initialSize = computeInitialSampleSize(options, minSideLength,  
  12.             maxNumOfPixels);  
  13.   
  14.     int roundedSize;  
  15.     if (initialSize <= 8) {  
  16.         roundedSize = 1;  
  17.         while (roundedSize < initialSize) {  
  18.             roundedSize <<= 1;  
  19.         }  
  20.     } else {  
  21.         roundedSize = (initialSize + 7) / 8 * 8;  
  22.     }  
  23.   
  24.     return roundedSize;  
  25. }  
  26.   
  27. /** 
  28.  * compute Initial Sample Size 
  29.  *  
  30.  * @param options 
  31.  * @param minSideLength 
  32.  * @param maxNumOfPixels 
  33.  * @return 
  34.  */  
  35. private static int computeInitialSampleSize(BitmapFactory.Options options,  
  36.         int minSideLength, int maxNumOfPixels) {  
  37.     double w = options.outWidth;  
  38.     double h = options.outHeight;  
  39.   
  40.     // 上下限範圍  
  41.     int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math  
  42.             .sqrt(w * h / maxNumOfPixels));  
  43.     int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(  
  44.             Math.floor(w / minSideLength), Math.floor(h / minSideLength));  
  45.   
  46.     if (upperBound < lowerBound) {  
  47.         // return the larger one when there is no overlapping zone.  
  48.         return lowerBound;  
  49.     }  
  50.   
  51.     if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
  52.         return 1;  
  53.     } else if (minSideLength == -1) {  
  54.         return lowerBound;  
  55.     } else {  
  56.         return upperBound;  
  57.     }  
  58. }  
以上參考一下,我們只需要使用此函數就行了:

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了:

  1. /** 
  2.  * get Bitmap 
  3.  *  
  4.  * @param imgFile 
  5.  * @param minSideLength 
  6.  * @param maxNumOfPixels 
  7.  * @return 
  8.  */  
  9. public static Bitmap tryGetBitmap(String imgFile, int minSideLength,  
  10.         int maxNumOfPixels) {  
  11.     if (imgFile == null || imgFile.length() == 0)  
  12.         return null;  
  13.   
  14.     try {  
  15.         FileDescriptor fd = new FileInputStream(imgFile).getFD();  
  16.         BitmapFactory.Options options = new BitmapFactory.Options();  
  17.         options.inJustDecodeBounds = true;  
  18.         // BitmapFactory.decodeFile(imgFile, options);  
  19.         BitmapFactory.decodeFileDescriptor(fd, null, options);  
  20.   
  21.         options.inSampleSize = computeSampleSize(options, minSideLength,  
  22.                 maxNumOfPixels);  
  23.         try {  
  24.             // 這裏一定要將其設置回false,因爲之前我們將其設置成了true  
  25.             // 設置inJustDecodeBounds爲true後,decodeFile並不分配空間,即,BitmapFactory解碼出來的Bitmap爲Null,但可計算出原始圖片的長度和寬度  
  26.             options.inJustDecodeBounds = false;  
  27.   
  28.             Bitmap bmp = BitmapFactory.decodeFile(imgFile, options);  
  29.             return bmp == null ? null : bmp;  
  30.         } catch (OutOfMemoryError err) {  
  31.             return null;  
  32.         }  
  33.     } catch (Exception e) {  
  34.         return null;  
  35.     }  
  36. }  

這樣,在BitmapFactory.decodeFile執行處,也就不會報出上面的OOM Error了。完美解決?如前面提到的,這種方式在一定程度上是以犧牲圖片質量爲代價的。如何才能更加優化的實現需求?


二、BitmapFactory.decodeFileDescriptor

當在android設備中載入較大圖片資源時,可以創建一些臨時空間,將載入的資源載入到臨時空間中。

1
2
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inTempStorage=new byte[12 *1024];
以上創建了一個12kb的臨時空間。然後使用Bitmap bitmapImage = BitmapFactory.decodeFile(path,bfOptions);但是我在程序中卻還是出現以上問題!以下使用BitmapFactory.decodeFileDescriptor解決了以上問題:

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()省內存

[java] view plaincopy
  1. FileInputStream is = = new FileInputStream(path);  
替換:

[java] view plaincopy
  1. Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);  
  2.    imageView.setImageBitmap(bmp);  
原因:
查看BitmapFactory的源碼,對比一下兩者的實現,可以發現decodeFile()最終是以流的方式生成bitmap 

decodeFile源碼:

[java] view plaincopy
  1. public static Bitmap decodeFile(String pathName, Options opts) {  
  2.     Bitmap bm = null;  
  3.     InputStream stream = null;  
  4.     try {  
  5.         stream = new FileInputStream(pathName);  
  6.         bm = decodeStream(stream, null, opts);  
  7.     } catch (Exception e) {  
  8.         /*  do nothing. 
  9.             If the exception happened on open, bm will be null. 
  10.         */  
  11.     } finally {  
  12.         if (stream != null) {  
  13.             try {  
  14.                 stream.close();  
  15.             } catch (IOException e) {  
  16.                 // do nothing here  
  17.             }  
  18.         }  
  19.     }  
  20.     return bm;  
  21. }  

decodeFileDescriptor的源碼,可以找到native本地方法decodeFileDescriptor,通過底層生成bitmap

decodeFileDescriptor源碼:

[java] view plaincopy
  1.    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {  
  2.        if (nativeIsSeekable(fd)) {  
  3.            Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);  
  4.            if (bm == null && opts != null && opts.inBitmap != null) {  
  5.                throw new IllegalArgumentException("Problem decoding into existing bitmap");  
  6.            }  
  7.            return finishDecode(bm, outPadding, opts);  
  8.        } else {  
  9.            FileInputStream fis = new FileInputStream(fd);  
  10.            try {  
  11.                return decodeStream(fis, outPadding, opts);  
  12.            } finally {  
  13.                try {  
  14.                    fis.close();  
  15.                } catch (Throwable t) {/* ignore */}  
  16.            }  
  17.        }  
  18.    }  
  19.   
  20. 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開發時,出現內存溢出是屬於系統底層限制,只要解碼需要的內存超過系統可分配的最大內存值,那麼內存溢出錯誤必然會出現。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章