无法使用BitmapFactory.decodeStream()从Url加载图像

时间:2012-01-25 23:27:19

标签: android image bitmapfactory

我正在尝试从URL下载图像以显示为ImageView。下载是在后台使用AsyncTask完成的。但是,对BitmapFactory的decodeStream的调用始终返回null对象。我验证了为连接提供的Url是正确的,但似乎BitmapFactory无法从HTTP连接返回的InputStream中读取图像。以下是代码:

@Override
    protected Bitmap doInBackground(String... uri) {
        Bitmap bm = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(Uri.encode(uri[0]));
        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            String contentType = entity.getContentType().getValue();
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int halfScreen = metrics.widthPixels / 2;
            int photoWidth = halfScreen > 200 ? 200 : halfScreen;
            if (contentType.contains("image/jpeg") || contentType.contains("image/png") || contentType.contains("image/gif")) {
                bm = BitmapFactory.decodeStream(new BufferedInputStream(entity.getContent()));
                if (bm.getWidth() > photoWidth)
                bm = Bitmap.createScaledBitmap(bm, photoWidth, Math.round((photoWidth*bm.getHeight())/bm.getWidth()), true);
            }
        } catch (Exception e) {
            bm = null;
        }
        return bm;
    }

奇怪的是,完全相同的代码在Nexus S上运行良好,但不适用于运行Android 2.1-update1的三星。

2 个答案:

答案 0 :(得分:3)

问题出在BitmapFactory.decodeStream()方法中。似乎这种方法有一个错误,使它在慢速连接上失败。我应用了http://code.google.com/p/android/issues/detail?id=6066中的建议。

我在下面创建了FlushedInputStream类:

public class FlushedInputStream extends FilterInputStream {

protected FlushedInputStream(InputStream in) {
    super(in);
}

@Override
public long skip(long n) throws IOException {
    long totalBytesSkipped = 0L;
    while (totalBytesSkipped < n) {
        long bytesSkipped = in.skip(n - totalBytesSkipped);
        if (bytesSkipped == 0L) {
              int onebyte = read();
              if (onebyte < 0) {
                  break;  // we reached EOF
              } else {
                  bytesSkipped = 1; // we read one byte
              }
       }
        totalBytesSkipped += bytesSkipped;
    }
    return totalBytesSkipped;
}
}

然后,在我使用的代码中:

bm = BitmapFactory.decodeStream(new FlushedInputStream(entity.getContent()));

而不是:

bm = BitmapFactory.decodeStream(new BufferedInputStream(entity.getContent()));

答案 1 :(得分:0)

尝试将您的HttpEntity包装到BufferedHttpEntity中,就像在这个问题中完成的那样:BitmapFactory.decodeStream returns null without exception。似乎问题非常相似。