[英]InputStream read twice when calculating sampled image?
我试图采用一种方法来防止从互联网位图读取时发生outOfMemoryError。 我使用对吗? 流不是从互联网读取两次吗?
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
URL url = new URL(imageUrl);
InputStream inputStream = url.openConnection().getInputStream();
BitmapFactory.decodeStream(inputStream, null, options);
// Calculate inSampleSize
int coverDimensions = CommonTasks.getDisplayMinSize(getActivity());
options.inSampleSize = calculateInSampleSize(options, coverDimensions, coverDimensions);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(inputStream, null, options);
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
在while
使用||
保持宽度和高度都没有限制。 不 ,您不能重新读取InputStream。
号理论上你可以使用reset()
,但互联网是顺序I / O:
boolen canReset = inputStream.markSupported();
if (canReset) {
inputStream.mark(Integer.MAX_VALUE);
}
... first read
if (canReset) {
inputStream.reset();
}
... second read
代替布尔标志,在重置时捕获IOException会更容易:例如,当超出读取限制时,可能会抛出该异常。
只需重新阅读即可。 第二次可能来自缓存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.