android BitmapFactory的OutOfMemoryError

網上有很多解決android加載bitmap內存溢出的方法,搜了一圈做下整理總結。項目里需求是拍攝多圖之后上傳,部分手機會內存溢出。

常用一種解決方法:即將載入的圖片縮小,這種方式以犧牲圖片的質量為代價。在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的值?每張圖片的放縮大小的比例應該是不一樣的!這樣的話就要運行時動態(tài)確定。在BitmapFactory.Options中提供了另一個成員inJustDecodeBounds。

設置inJustDecodeBounds為true后,decodeFile并不分配空間,但可計算出原始圖片的長度和寬度,即opts.width和opts.height。有了這兩個參數,再通過一定的算法,即可得到一個恰當的inSampleSize。Android提供了一種動態(tài)計算的方法,見computeSampleSize().

publicstaticintcomputeSampleSize(BitmapFactory.Options options,intminSideLength,intmaxNumOfPixels){intinitialSize = computeInitialSampleSize(options, minSideLength,? ? ? ? ? ? maxNumOfPixels);introundedSize;if(initialSize <=8) {? ? ? ? roundedSize =1;while(roundedSize < initialSize) {? ? ? ? ? ? roundedSize <<=1;? ? ? ? }? ? }else{? ? ? ? roundedSize = (initialSize +7) /8*8;? ? }returnroundedSize;}privatestaticintcomputeInitialSampleSize(BitmapFactory.Options options,intminSideLength,intmaxNumOfPixels){doublew = options.outWidth;doubleh = options.outHeight;intlowerBound = (maxNumOfPixels == -1) ?1:? ? ? ? ? ? (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));intupperBound = (minSideLength == -1) ?128:? ? ? ? ? ? (int) Math.min(Math.floor(w / minSideLength),? ? ? ? ? ? Math.floor(h / minSideLength));if(upperBound < lowerBound) {returnlowerBound;? ? }if((maxNumOfPixels == -1) &&? ? ? ? ? ? (minSideLength == -1)) {return1;? ? }elseif(minSideLength == -1){returnlowerBound;? ? }else{returnupperBound;? ? }}

以上只做為參考,我們只要用這函數即可,opts.inSampleSize = computeSampleSize(opts, -1,128*128);

要點:

1、用decodeFileDescriptor()來生成bimap比decodeFile()省內存

FileInputStreamis= =newFileInputStream(path);bmp = BitmapFactory.decodeFileDescriptor(is.getFD(),null, opts);

替換

Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);? ? imageView.setImageBitmap(bmp);

原因:

查看BitmapFactory的源碼,對比一下兩者的實現,可以發(fā)現decodeFile()最終是以流的方式生成bitmap

decodeFile源碼:

publicstaticBitmapdecodeFile(String pathName, Options opts){? ? ? ? Bitmap bm =null;? ? ? ? InputStream stream =null;try{? ? ? ? ? ? stream =newFileInputStream(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}? ? ? ? ? ? }? ? ? ? }returnbm;? ? }

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

decodeFileDescriptor源碼:

publicstaticBitmapdecodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts){if(nativeIsSeekable(fd)) {? ? ? ? ? ? Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);if(bm ==null&& opts !=null&& opts.inBitmap !=null) {thrownewIllegalArgumentException("Problem decoding into existing bitmap");? ? ? ? ? ? }returnfinishDecode(bm, outPadding, opts);? ? ? ? }else{? ? ? ? ? ? FileInputStream fis =newFileInputStream(fd);try{returndecodeStream(fis, outPadding, opts);? ? ? ? ? ? }finally{try{? ? ? ? ? ? ? ? ? ? fis.close();? ? ? ? ? ? ? ? }catch(Throwable t) {/* ignore */}? ? ? ? ? ? }? ? ? ? }? ? }privatestaticnativeBitmapnativeDecodeFileDescriptor(FileDescriptor fd,Rect padding, Options opts);

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

opts.inTempStorage =newbyte[16*1024];

?

完整代碼:

publicstaticOutputStream decodeBitmap(Stringpath) {BitmapFactory.Options opts =newBitmapFactory.Options();opts.inJustDecodeBounds =true;// 設置成了true,不占用內存,只獲取bitmap寬高BitmapFactory.decodeFile(path, opts);opts.inSampleSize = computeSampleSize(opts, -1,1024*800);opts.inJustDecodeBounds =false;// 這里一定要將其設置回false,因為之前我們將其設置成了trueopts.inPurgeable =true;opts.inInputShareable =true;opts.inDither =false;opts.inPurgeable =true;opts.inTempStorage =newbyte[16*1024];FileInputStream is =null;Bitmap bmp =null;InputStream ins =null;ByteArrayOutputStream baos =null;try{is =newFileInputStream(path);bmp = BitmapFactory.decodeFileDescriptor(is.getFD(),null, opts);doublescale= getScaling(opts.outWidth * opts.outHeight,1024*600);Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,(int) (opts.outWidth *scale),(int) (opts.outHeight *scale),true);bmp.recycle();baos =newByteArrayOutputStream();bmp2.compress(Bitmap.CompressFormat.JPEG,100, baos);bmp2.recycle();returnbaos;}catch(FileNotFoundException e) {e.printStackTrace();}catch(IOException e) {e.printStackTrace();}finally{try{is.close();ins.close();baos.close();}catch(IOException e) {e.printStackTrace();}System.gc();}returnbaos;}privatestaticdoublegetScaling(intsrc,intdes) {/**

* 目標尺寸÷原尺寸 sqrt開方,得出寬高百分比

*/doublescale= Math.sqrt((double) des / (double) src);returnscale;}




http://my.oschina.net/jeffzhao/blog/80900

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容