原文鏈接:http://www.ytsyt.cn/post/7.html
先轉(zhuǎn)載收藏样悟!
手機(jī)的拍照像素越來越高劲适,拍出來的照片效果也會越來越好碾篡,但是像素高了照片的容量也就變大了铡羡,如果不能處理好bitmap的話很容易導(dǎo)致OOM異常的拭嫁。以下提供3種解決OOM異常的方案:?
一民假、bitmap不用就就回收掉?
Java protected void onDestroy() {?
? ? ? super.onDestroy();
? ? ? if(bmp1 != null){?
? ? ? ? ? ? bmp1.recycle();?
? ? ? ? ? ? ?bmp1 = null;
? ? ? ? }?
? ? ? ? if(bmp2 != null){
? ? ? ? ? ? ? bmp2.recycle();
? ? ? ? ? ? ? bmp2 = null;
? ? ? ? ?}
?}?
二浮入、先算出該bitmap的大小,然后通過調(diào)節(jié)采樣率的方式來規(guī)避羊异,也就是等比例壓縮?
Java BitmapFactory.Options opts = new BitmapFactory.Options();?
opts.inJustDecodeBounds = true;?
BitmapFactory.decodeFile(imageFile, opts);
?opts.inSampleSize = computeSampleSize(opts, minSideLength, maxNumOfPixels);?
opts.inJustDecodeBounds = false;?
try {?
? ? ? ? ?return BitmapFactory.decodeFile(imageFile, opts);?
} catch (OutOfMemoryError err) { }
?return null;
?三事秀、在進(jìn)行文件傳輸時(shí),最好采用壓縮的方式變成byte[]再傳輸?
Java public static byte[] bitmap2Bytes(Bitmap bm) {?
? ? ? ? ?ByteArrayOutputStream baos = new ByteArrayOutputStream();?
? ? ? ? ?bm.compress(Bitmap.CompressFormat.JPEG, 90, baos);?
? ? ? ? ?return baos.toByteArray();
?}