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

发布于 2024-12-29 12:34:05 字数 1426 浏览 1 评论 0原文

我正在尝试从 URL 下载图像以显示为 ImageView。下载是使用 AsyncTask 在后台完成的。然而,对BitmapFactory的decodeStream的调用总是返回一个空对象。我验证了为连接提供的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 的三星上却不起作用。

I am trying to download an image from a URL to display as an ImageView. The download is done in the background using AsyncTask. However, the call to the decodeStream of the BitmapFactory always returns a null object. I verified that the Url provided for the connection is right, but it seems that BitmapFactory cannot read the image from the InputStream returned by the HTTP connection. Here is the code below:

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

What is weird is that the exact same code runs fine on a Nexus S, but does not work on a Samsung running Android 2.1-update1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凡尘雨 2025-01-05 12:34:05

问题出在 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()));

The problem was in the BitmapFactory.decodeStream() method. It seems that this method has a bug that makes it fail on slow connections. I applied the recommendations found at http://code.google.com/p/android/issues/detail?id=6066.

I created the FlushedInputStream class below:

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

Then, in my code I used:

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

instead of:

bm = BitmapFactory.decodeStream(new BufferedInputStream(entity.getContent()));
2025-01-05 12:34:05

尝试将您的 HttpEntity 包装到 BufferedHttpEntity 中,就像在这个问题中所做的那样: BitmapFactory.decodeStream returns null无一例外。看来这个问题很相似。

Try to wrap your HttpEntity into BufferedHttpEntity, like it's done in this question: BitmapFactory.decodeStream returns null without exception . Seems that problem is quite similar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文