BitmapFactory.decodeStream在不抛出异常的情况下返回null

8

我尝试从服务器加载远程图片,感谢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,这表示出现了错误,但没有抛出异常,所以我无法确定具体出了什么问题。输入流始终返回有效值,并且我知道图片在服务器上存在。

祝好, Daniel

1个回答

16

我在这里找到了答案(链接),并更新了获取方法:

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下载每个图像)。至少它能工作。 - kellogs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接