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;

最佳答案

您随时可以从URL重新打开流

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()

关于java - 当BitmapFactory.decodeStream(stream,null,options)时重用InputStream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18768422/

10-12 03:57
查看更多