BitmapFactory.decodeStream(InputStream is) returns null for non null InputStream on Android

后端 未结 3 1275
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 19:54

I\'m developing an Android application, and it\'s view is containing multiple Gallerys. The content of the Gallerys (the Bitmaps) are red from the Internet.

For the

3条回答
  •  孤街浪徒
    2020-12-06 20:42

    I've run into this. Try using BufferedHttpEntity with your inputstream. I found this prevented 99.9% of the issues with getting silent nulls from decodeStream.

    Maybe not signficant, but I reliably use org.apache.http.client.HttpClient rather than HttpURLConnection as in:

    public static Bitmap decodeFromUrl(HttpClient client, URL url, Config bitmapCOnfig)
    {
        HttpResponse response=null;
        Bitmap b=null;
        InputStream instream=null;
    
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        decodeOptions.inPreferredConfig = bitmapCOnfig;
        try
        {
        HttpGet request = new HttpGet(url.toURI());
            response = client.execute(request);
            if (response.getStatusLine().getStatusCode() != 200)
            {
                MyLogger.w("Bad response on " + url.toString());
                MyLogger.w ("http response: " + response.getStatusLine().toString());
                return null;
            }
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity());
            instream = bufHttpEntity.getContent();
    
            return BitmapFactory.decodeStream(instream, null, decodeOptions);
        }
        catch (Exception ex)
        {
            MyLogger.e("error decoding bitmap from:" + url, ex);
            if (response != null)
            {
                MyLogger.e("http status: " + response.getStatusLine().getStatusCode());
            }
            return null;
        }
        finally
        {
            if (instream != null)
            {
                try {
                    instream.close();
                } catch (IOException e) {
                    MyLogger.e("error closing stream", e);
                }
            }
        }
    }
    

提交回复
热议问题