背景
假设我有一个源自某个图像文件的互联网的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
为了从网址中获取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;
}
这个问题
如何让代码处理标记重置?
它与资源完美配合(实际上我甚至不需要创建一个新的BufferedInputStream来实现)但不能使用来自互联网的inputStream …
编辑:
看来我的代码很好,有点……
在某些网站上(如this one和this one),即使重置后也无法解码图像文件.
如果您解码位图(并使用inSampleSize),它可以解码它(只需要很长时间).
现在的问题是它为什么会发生,我该如何解决它.
解决方法:
我认为问题在于对标记(1024)的调用会覆盖带有大值的mark().如文档中所述:
Prior to KITKAT, if is.markSupported() returns true, is.mark(1024) would be called. As of KITKAT, this is no longer the case.
如果读取大于此值的读取,则可能导致reset()失败.