Android 圖片質量壓縮問題
本帖最后由 u013064347 于 2014-01-13 10:22:47 編輯
網上看到一個圖片質量壓縮法,傳入1M以內圖片能正常壓縮,但是傳入2M多的圖片就報內存溢出,應該怎么解決?附上代碼
Bitmap?images=BitmapFactory.decodeFile(filePath);//這里傳入圖片會報內存溢出!
public?Bitmap?compressImage(Bitmap?image)?{
ByteArrayOutputStream?baos?=?new?ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG,?100,?baos);//?質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中
int?options?=?90;
int?longs=baos.toByteArray().length;
while?(baos.toByteArray().length/1024??>?100)?{?//?循環判斷如果壓縮后圖片是否大于100kb,大于繼續壓縮
baos.reset();//?重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG,?options,?baos);//?這里壓縮options%,把壓縮后的數據存放到baos中
longs=baos.toByteArray().length;
options?-=?10;//?每次都減少10
}
ByteArrayInputStream?isBm?=?new?ByteArrayInputStream(baos.toByteArray());//?把壓縮后的數據baos存放到ByteArrayInputStream中
Bitmap?bitmap?=?BitmapFactory.decodeStream(isBm,?null,?null);//?把ByteArrayInputStream數據生成圖片
return?bitmap;
}
分享到:
更多
------解決方案--------------------
//?取得圖片
InputStream?temp?=?this.getAssets().open(path);
BitmapFactory.Options?options?=?new?BitmapFactory.Options();
//?這個參數代表,不為bitmap分配內存空間,只記錄一些該圖片的信息(例如圖片大小),說白了就是為了內存優化
options.inJustDecodeBounds?=?true;
//?通過創建圖片的方式,取得options的內容(這里就是利用了java的地址傳遞來賦值)
BitmapFactory.decodeStream(temp,?null,?options);
//?關閉流
temp.close();
//?生成壓縮的圖片
int?i?=?0;
Bitmap?bitmap?=?null;
while?(true)?{
//?這一步是根據要設置的大小,使寬和高都能滿足
if?((options.outWidth?>>?i?<=?size)
&&?(options.outHeight?>>?i?<=?size))?{
//?重新取得流,注意:這里一定要再次加載,不能二次使用之前的流!
temp?=?this.getAssets().open(path);
//?這個參數表示?新生成的圖片為原始圖片的幾分之一。
options.inSampleSize?=?(int)?Math.pow(2.0D,?i);
//?這里之前設置為了true,所以要改為false,否則就創建不出圖片
options.inJustDecodeBounds?=?false;
bitmap?=?BitmapFactory.decodeStream(temp,?null,?options);
break;
}
i?+=?1;
}
return?bitmap;
------解決方案--------------------
http://bbs.csdn.net/topics/390432950