近日在做bitmap異步加載時,發現BitmapFactory.decodeStream返回null,問題就在於我們調用了兩次decodeStream。第一次用於獲取圖片的原始大小,第二次才用於decode。解決方法也較簡單,就是將byte[]作爲中間變量進行轉換。大牛原博客鏈接Android異步從網絡加載圖片BitmapFactory.decodeStream 返回null的問題
1.將獲得的inputStream轉換成byte[]
private static byte[] inputStream2ByteArr(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ( (len = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
inputStream.close();
outputStream.close();
return outputStream.toByteArray();
}
public static Bitmap decodeSampleBitMapByByteArr(InputStream inputStream,int reqWidth,int reqHeight) throws IOException{
if (inputStream == null) {
return null;
}
BitmapFactory.Options options = new BitmapFactory.Options();
//設置該屬性可以不佔用內存,並且能夠得到bitmap的寬高等屬性,此時得到的bitmap是空
options.inJustDecodeBounds = true;
byte[] data = inputStream2ByteArr(inputStream);//將InputStream轉爲byte數組,可以多次讀取
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
//設置計算得到的壓縮比例
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//設置爲false,確保可以得到bitmap != null
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
return bitmap;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 源圖片的高度和寬度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// 計算出實際寬高和目標寬高的比率
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 選擇寬和高中最小的比率作爲inSampleSize的值,這樣可以保證最終圖片的寬和高
// 一定都會大於等於目標的寬和高。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}