问题描述
我试图从URL下载的图像显示为一个ImageView的。下载使用的AsyncTask在后台完成。然而,在调用BitmapFactory的德codeStream总是返回一个空的对象。我核实,提供连接的URL是正确的,但似乎BitmapFactory无法读取通过HTTP连接返回的InputStream的形象。这里是低于code:
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;
}
什么是奇怪的是完全相同的code运行在Nexus S的罚款,但在三星运行Android 2.1 UPDATE1不起作用。
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.
推荐答案
的问题是在BitmapFactory.de codeStream()方法。看来,这个方法,使得它无法在连接速度慢的错误。我申请在。
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.
我创建以下FlushedInputStream类:
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;
}
}
然后,在我的code我用:
Then, in my code I used:
bm = BitmapFactory.decodeStream(new FlushedInputStream(entity.getContent()));
而不是:
bm = BitmapFactory.decodeStream(new BufferedInputStream(entity.getContent()));
这篇关于不能使用BitmapFactory.de codeStream URL加载图像()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!