【发布时间】:2011-01-31 00:15:11
【问题描述】:
我遇到了BitmapFactory.decodeStream(inputStream) 的问题。当不带选项使用它时,它将返回一个图像。但是当我将它与.decodeStream(inputStream, null, options) 中的选项一起使用时,它永远不会返回位图。
我要做的是在实际加载位图之前对其进行下采样以节省内存。
我读过一些很好的指南,但没有使用.decodeStream。
工作正常
URL url = new URL(sUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is, null, options);
不起作用
InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is, null, options);
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH);
if (options.outHeight * options.outWidth * 2 >= 200*100*2){
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / TARGET_HEIGHT
: options.outWidth / TARGET_WIDTH;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
Bitmap img = BitmapFactory.decodeStream(is, null, options);
【问题讨论】:
-
System.out.println("Samplesize: " ...) 语句的输出是什么?是否表明 options.inSampleSize 是可接受的值?
-
是的,它每次都返回一个可接受的值。
-
由于正在调试,删除了该语句。
-
感谢您发布您的解决方案,但还有一件事要做。此问题仍会出现在“未解决的问题”列表中,因为您尚未将回复标记为“已接受”。您可以通过单击答案旁边的勾号图标来做到这一点。如果您觉得 Samuh 的答案有助于您找到解决方案,您可以接受它,或者您可以发布自己的答案并接受它。 (通常您会将您的解决方案放在您的答案中,但由于您已经通过编辑您的问题将其包含在内,您可以将它们引向该问题。)
-
感谢您帮助新用户融入社区 :)