我试图从 InputStream 调整一张图像的大小,所以我使用了 Strange out of memory issue while loading an image to a Bitmap object 中的代码但我不知道为什么这段代码总是返回没有图像的 Drawable。
这个效果很好:
private Drawable decodeFile(InputStream f){
try {
InputStream in2 = new BufferedInputStream(f);
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=2;
return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
} catch (Exception e) {
return null;
}
}
这个不行:
private Drawable decodeFile(InputStream f){
try {
InputStream in1 = new BufferedInputStream(f);
InputStream in2 = new BufferedInputStream(f);
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in1,null,o);
//The new size we want to scale to
final int IMAGE_MAX_SIZE=90;
//Find the correct scale value. It should be the power of 2.
int scale = 2;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = false;
o2.inSampleSize=scale;
return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
} catch (Exception e) {
return null;
}
}
为什么一个选项会影响另一个选项?如果我使用两个不同的 InputStream 和 Options 怎么可能?
最佳答案
实际上您有两个不同的 BufferedInputStream
但它们在内部使用唯一的一个 InputStream
对象,因为 BufferedInputStream
只是 InputStream 的包装器
。
所以你不能在同一个流上调用两次 BitmapFactory.decodeStream
方法,它肯定会失败,因为第二次它不会从流的开头开始解码。如果支持或重新打开流,您需要重置流。
关于android - 从 InputStream 调整位图大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841482/