Java代碼
public Bitmap optimizeBitmap(byte[] source, int maxWidth, int maxHeight) {
Bitmap result = null;
int length = source.length;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
result = BitmapFactory.decodeByteArray(source, 0, length, options);
int widthRatio = (int) Math.ceil(options.outWidth / maxWidth);
int heightRatio = (int) Math.ceil(options.outHeight / maxHeight);
if(widthRatio > 1 || heightRatio > 1) {
if(widthRatio > heightRatio) {
options.inSampleSize = widthRatio;
} else {
options.inSampleSize = heightRatio;
}
}
options.inJustDecodeBounds = false;
result = BitmapFactory.decodeByteArray(source, 0, length, options);
return result;
}
Android Emulator的內存隻有8M,當需要顯示較多大圖時,極易拋出“bitmap size exceeds VM budget ”的異常。
BitmapFactory.Options的公有boolean型成員變量inJustDecodeBounds,當值設置為true時,解碼器返回NULL,我們可以在圖像未加載內存的情況下查詢圖像。
示例代碼中,我們通過Options對象實例options獲得瞭圖像的寬度和高度。
BitmapFactory.Options的公有int型成員變量inSampleSize用於設置圖像的縮小比例,例如當inSampleSize設置為4時,編碼器將返回原始1/4大小的圖像。
註意:需要編碼器返回圖像時,記得將inJustDecodeBounds的值設為false。
作者“Dyingbleed”