網(wǎng)上有很多解決android加載bitmap內(nèi)存溢出的方法撒犀,搜了一圈做下整理總結(jié)偎箫。項目里需求是拍攝多圖之后上傳蔑舞,部分手機會內(nèi)存溢出。
常用一種解決方法:即將載入的圖片縮小殷费,這種方式以犧牲圖片的質(zhì)量為代價印荔。在BitmapFactory中有一個內(nèi)部類BitmapFactory.Options低葫,其中當options.inSampleSize值>1時,根據(jù)文檔:
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的指數(shù)的倒數(shù)被進行放縮
現(xiàn)在問題是怎么確定inSampleSize的值仍律?每張圖片的放縮大小的比例應該是不一樣的嘿悬!這樣的話就要運行時動態(tài)確定。在BitmapFactory.Options中提供了另一個成員inJustDecodeBounds水泉。
設(shè)置inJustDecodeBounds為true后善涨,decodeFile并不分配空間,但可計算出原始圖片的長度和寬度茶行,即opts.width和opts.height躯概。有了這兩個參數(shù),再通過一定的算法畔师,即可得到一個恰當?shù)膇nSampleSize娶靡。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;? ? }}
以上只做為參考看锉,我們只要用這函數(shù)即可姿锭,opts.inSampleSize = computeSampleSize(opts, -1,128*128);
要點:
1、用decodeFileDescriptor()來生成bimap比decodeFile()省內(nèi)存
FileInputStreamis= =newFileInputStream(path);bmp = BitmapFactory.decodeFileDescriptor(is.getFD(),null, opts);
替換
Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);? ? imageView.setImageBitmap(bmp);
原因:
查看BitmapFactory的源碼伯铣,對比一下兩者的實現(xiàn)呻此,可以發(fā)現(xiàn)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設(shè)備中載入較大圖片資源時,可以創(chuàng)建一些臨時空間放前,將載入的資源載入到臨時空間中忿磅。
opts.inTempStorage =newbyte[16*1024];
完整代碼:
publicstaticOutputStream decodeBitmap(Stringpath) {BitmapFactory.Options opts =newBitmapFactory.Options();opts.inJustDecodeBounds =true;// 設(shè)置成了true,不占用內(nèi)存,只獲取bitmap寬高BitmapFactory.decodeFile(path, opts);opts.inSampleSize = computeSampleSize(opts, -1,1024*800);opts.inJustDecodeBounds =false;// 這里一定要將其設(shè)置回false凭语,因為之前我們將其設(shè)置成了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