BitmapFactory.decodeStream not working

╄→尐↘猪︶ㄣ 提交于 2019-12-25 03:58:20

问题


I'm having a bit of a problem with decodeStream returning null. It seems to be a fairly common problem around, but it's usually pinned down to one of two problems:

  • An OutOfMemory exception thrown by attempting to load a large bitmap in it's entirety.
  • Attempting to use the same input stream twice.

However, I'm not doing either. The code to run it is simply

stream = new java.net.URL(url).openStream();
Bitmap image = BitmapFactory.decodeStream(stream);
stream.close();

with the URL set to here. image is null after this code is complete. This issue's been driving me completely insane - it works fine on PNGs but seems to fall apart under every BMP I can give it, so any help would be appreciated.


回答1:


Ultimately, the answer was found here, using an InputStream returned by a BufferedHTTPEntity. While it seems needlessly complex, I can only assume that simply getting a stream from the URL object directly doesn't return a stream of the appropriate type, and so it wasn't reading out all the data properly.

Cross-posting the code in case the question is erased:

private static InputStream fetch(String address) throws MalformedURLException,IOException {
    HttpGet httpRequest = new HttpGet(URI.create(address) );
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream instream = bufHttpEntity.getContent();
    return instream;
}


来源:https://stackoverflow.com/questions/23096962/bitmapfactory-decodestream-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!