如何获取位图信息,然后从internet-inputStream解码位图?

and*_*per 9 android inputstream bitmap reset

背景

假设我有一个源自某个图像文件的互联网的inputStream.

我希望获得有关图像文件的信息,然后才能对其进行解码.

它可用于多种用途,例如下采样以及在显示图像之前预览信息.

问题

我试图通过使用BufferedInputStream包装inputStream来标记和重置inputStream,但它不起作用:

inputStream=new BufferedInputStream(inputStream);
inputStream.mark(Integer.MAX_VALUE);
final BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeStream(inputStream,null,options);
//this works fine. i get the options filled just right.

inputStream.reset();
final Bitmap bitmap=BitmapFactory.decodeStream(inputStream,null,options);
//this returns null
Run Code Online (Sandbox Code Playgroud)

为了从网址中获取inputStream,我使用:

public static InputStream getInputStreamFromInternet(final String urlString)
  {
  try
    {
    final URL url=new URL(urlString);
    final HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
    final InputStream in=urlConnection.getInputStream();
    return in;
    }
  catch(final Exception e)
    {
    e.printStackTrace();
    }
  return null;
  }
Run Code Online (Sandbox Code Playgroud)

这个问题

如何让代码处理标记重置?

它与资源完美配合(实际上我甚至不需要创建一个新的BufferedInputStream来实现)但不能使用来自互联网的inputStream ...


编辑:

看来我的代码很好,有点......

在一些网站上(比如这一个这个),即使重置后也无法解码图像文件.

如果您解码位图(并使用inSampleSize),它可以解码它(只需要很长时间).

现在的问题是它为什么会发生,我该如何解决它.

Jef*_*man -1

是否可以标记/重置流取决于流的实现。这些是可选操作,通常不受支持。您的选择是将流读入缓冲区,然后从该流中读取 2x,或者只是将网络连接设置为 2x。

最简单的事情可能是写入ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
int count;
byte[] b = new byte[...];
while ((count = input.read(b) != -1) [
  baos.write(b, 0, count);
}
Run Code Online (Sandbox Code Playgroud)

现在要么直接使用结果baos.toByteArray(),要么创建一个ByteArrayInputStream并重复使用它,reset()每次使用后调用。

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
Run Code Online (Sandbox Code Playgroud)

这可能听起来很傻,但是这并没有什么魔力。您要么将数据缓冲在内存中,要么从源中读取数据 2 倍。如果流确实支持标记/重置,则它必须在其实现中执行相同的操作。