簡單吹下牛:很多app都會要加載圖片晒他,但是如果不壓縮圖片就很容易OOM,
個人看來OOM 出現(xiàn)原因總的來說分為兩種:
一種是內存溢出(好像在扯淡,OOM本身就是內存溢出)
另一種是:圖片過大尊勿,一個屏幕顯示不完全造成,似乎也是一伍纫。噪沙。 如有錯誤純屬扯淡;
為了避免上面的情況:加載圖片的時候可以進行壓縮哄辣,上傳的時候要可以進行壓縮请梢,在圖片不可見的時候進行回收(onDetach()),再吹一句 用了fresco+壓縮之后加載圖片完全沒問題了。
一柔滔、質量壓縮方法:
privateBitmap compressImage(Bitmap image) {
ByteArrayOutputStream?baos?=newByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG,100,?baos);//質量壓縮方法溢陪,這里100表示不壓縮萍虽,把壓縮后的數(shù)據存放到baos中
intoptions?=100;
while(?baos.toByteArray().length?/1024>100)?{//循環(huán)判斷如果壓縮后圖片是否大于100kb,大于繼續(xù)壓縮
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG,?options,?baos);//這里壓縮options%睛廊,把壓縮后的數(shù)據存放到baos中
options?-=10;//每次都減少10
}
ByteArrayInputStream?isBm?=newByteArrayInputStream(baos.toByteArray());//把壓縮后的數(shù)據baos存放到ByteArrayInputStream中
Bitmap?bitmap?=?BitmapFactory.decodeStream(isBm,null,null);//把ByteArrayInputStream數(shù)據生成圖片
returnbitmap;
}
二、圖片按比例大小壓縮方法(根據Bitmap圖片壓縮)
privateBitmap comp(Bitmap image) {
ByteArrayOutputStream?baos?=newByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG,100,?baos);
if(?baos.toByteArray().length?/1024>1024)?{//判斷如果圖片大于1M,進行壓縮避免在生成圖片(BitmapFactory.decodeStream)時溢出
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG,50,?baos);//這里壓縮50%杉编,把壓縮后的數(shù)據存放到baos中
}
ByteArrayInputStream?isBm?=newByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options?newOpts?=newBitmapFactory.Options();
//開始讀入圖片超全,此時把options.inJustDecodeBounds?設回true了
newOpts.inJustDecodeBounds?=true;
Bitmap?bitmap?=?BitmapFactory.decodeStream(isBm,null,?newOpts);
newOpts.inJustDecodeBounds?=false;
intw?=?newOpts.outWidth;
inth?=?newOpts.outHeight;
//現(xiàn)在主流手機比較多是800*480分辨率,所以高和寬我們設置為
floathh?=?800f;//這里設置高度為800f
floatww?=?480f;//這里設置寬度為480f
//縮放比邓馒。由于是固定比例縮放嘶朱,只用高或者寬其中一個數(shù)據進行計算即可
intbe?=1;//be=1表示不縮放
if(w?>?h?&&?w?>?ww)?{//如果寬度大的話根據寬度固定大小縮放
be?=?(int)?(newOpts.outWidth?/?ww);
}elseif(w?<?h?&&?h?>?hh)?{//如果高度高的話根據寬度固定大小縮放
be?=?(int)?(newOpts.outHeight?/?hh);
}
if(be?<=0)
be?=1;
newOpts.inSampleSize?=?be;//設置縮放比例
//重新讀入圖片,注意此時已經把options.inJustDecodeBounds?設回false了
isBm?=newByteArrayInputStream(baos.toByteArray());
bitmap?=?BitmapFactory.decodeStream(isBm,null,?newOpts);
returncompressImage(bitmap);//壓縮好比例大小后再進行質量壓縮
}