【发布时间】:2015-09-23 07:31:36
【问题描述】:
我想将图像从“http://i.imgur.com/4GLKF4Q.jpg”显示到 ImageView,但图像 URL 中的图像没有显示到 imageview。我可以这样做吗?
异步任务
class DownloadImageTask extends AsyncTask<String, Void, byte[]> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected byte[] doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(byte[] result) {
ByteArrayInputStream imageStream = new ByteArrayInputStream(result);
Bitmap bm = BitmapFactory.decodeStream(imageStream);
bmImage.setImageBitmap(bm);
}
}
活动中
new DownloadImageTask((ImageView) newView.findViewById(R.id.thumbnail))
.execute("http://i.imgur.com/4GLKF4Q.jpg");
图片 URL 中的图片没有显示到 imageview。 在 Logcat 中:
09-23 10:26:49.410 10591-10591/com.*** D/skia: --- SkImageDecoder::Factory returned null
【问题讨论】:
-
更好的方法是使用 AQuery code.google.com/p/android-query 或 Picasso github.com/square/picasso
-
这个问题已经被问过很多次了,但大多数答案都已经过时了。现代方法是使用 NetworkImageView 请在下面查看我的答案。
标签: java android url imageview