BitmapFactory.decodeStream(stream,null,options)时重用InputStream

时间:2013-09-12 15:28:59

标签: java android inputstream

InputStream stream = new URL(key).openStream();

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

BitmapFactory.decodeStream(stream, null, options);

options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);
options.inJustDecodeBounds = false;

/* i need reuse stream here, for decode stream again. */

Bitmap bmp = BitmapFactory.decodeStream(stream, null, options);

stream.close();

return bmp;

1 个答案:

答案 0 :(得分:0)

您始终只需从网址

重新打开流即可
InputStream stream = new URL(key).openStream();

或者我们像Guava这样的库(ByteStreams)来完全阅读InputStream并将结果字节分配到ByteArrayInputStream

InputStream stream = new URL(key).openStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteStreams.copy(stream, out);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

// use it once
in.reset();
// use it again

如果您的代码在流上调用mark(),请小心。如果发生这种情况,只需使用ByteArrayInputStream ByteArrayOutputStream中的字节创建一个新的out.toByteArray()