正常的圖片縮放代碼如:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
arg1.compress(Bitmap.CompressFormat.JPEG, 100, baos);//arg1為傳進來的原始bitmap
baos.toByteArray();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
//進行縮放
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開始讀入圖片,此時把options.inJustDecodeBounds 設回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(is,null,newOpts);// 此時返回bm為空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 現在主流手機比較多是800*480分辨率,所以高和寬我們設置為
float hh = 100f;// 這里設置高度為800f
float ww = 100f;// 這里設置寬度為480f
// 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
int be = 1;// be=1表示不縮放
if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = 2;// 設置縮放比例
// 重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
最后取得bitmap竟然為空,百思不得起解,然后將bitmap獲取方式改為BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, newOpts)就能獲取到了,這個真難道是android的一個bug?
原文:http://my.oschina.net/u/1463920/blog/360901