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 表示错误,但没有抛出异常,所以我真的无法判断出了什么问题。InputStream 总是返回一个有效值,我知道图片存在于服务器上。

最良好的祝愿,丹尼尔

4

1 回答 1

16

我在这里找到了答案并将 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;
}
于 2010-12-11T13:01:28.757 回答