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”