gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:09:54 24 4
gpt4 key购买 nike

我正在尝试从 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 的三星上却不起作用。

最佳答案

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

关于android - 无法使用 BitmapFactory.decodeStream() 从 Url 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9011967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com