BitmapFactory.decodeStream无异常返回null

时间:2010-12-11 02:16:33

标签: android bitmapfactory

我尝试从服务器加载远程图像,并且由于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表示错误,但没有抛出Exception,所以我无法确定出现了什么问题。 InputStream总是返回一个有效值,我知道服务器上存在该图片。

祝福, 丹尼尔

1 个答案:

答案 0 :(得分:16)

我找到了答案here并将获取方法更新为:

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