近日在做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;
}