【问题标题】:BitmapFactory.decodeStream returns null without exceptionBitmapFactory.decodeStream 无异常返回 null
【发布时间】:2011-05-23 19:48:07
【问题描述】:

我尝试从服务器加载远程图像,并且感谢 stackoverflow 上的大量代码示例,我有一个解决方案,它适用于 3 个图像中的 2 个。我真的不知道第三张图片有什么问题,有时当让代码在调试器中运行时,图片正在加载。另外,如果我先加载问题图片,其他两张图片有时不会加载。

代码如下:

public static Drawable getPictureFromURL(Context ctx, String url, final int REQUIRED_SIZE) throws NullPointerException {
    //Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    int scale = 1;
    if (o.outWidth > REQUIRED_SIZE) {
        scale = (int) Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
    }
    Log.i(Prototype.TAG, "scale: "+scale); 

    //Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bmp;
    try {
        bmp = BitmapFactory.decodeStream((InputStream) Tools.fetch(url), null, o2);
        if(bmp!=null)
            return new BitmapDrawable(ctx.getResources(), bmp);
        else
            return null;
    } catch (Exception e) {
        Log.e(Prototype.TAG, "Exception while decoding stream", e);
        return null;
    }
}

在调试过程中,我发现 o.outWidth 为 -1 表示错误,但没有抛出异常,所以我无法真正判断出了什么问题。 InputStream 总是返回一个有效值,我知道图片存在于服务器上。

最好的祝愿, 丹尼尔

【问题讨论】:

    标签: android bitmapfactory


    【解决方案1】:

    我找到了答案here,并将 fetch 方法更新为:

    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;
    }
    

    【讨论】:

    • +1,但现在似乎图像是按顺序而不是并行下载的(我在单独的 AsyncTask 上对每个图像进行 dl-ing)。至少它有效..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多