我有一个ImageView,我需要做的就是在应用程序加载时从intetrnet中显示图像。有没有一个非常简单的方法来做到这一点?Android - 如何显示来自URL的图像?
回答
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
Bitmap bitmap = BitmapFactory.decodeStream(response.getEntity().getContent());
client.execute(get);立即得到下划线,并且错误显示“未处理的异常类型ClientProtocolException” – 2011-05-03 16:37:06
因此,处理异常类型...将它围绕在try/catch中 – 2011-05-03 16:41:51
做了那个。 FC和崩溃。为什么我应该得到那个错误? – 2011-05-03 16:42:25
ImageView.setImageURI
似乎不适用于互联网资源,所以您应该自己阅读位图。
InputStream is = new URL("http://example.com/myimage.jpg").openStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
ImageView iv = (ImageView) findViewById(R.id.myImage);
iv.setImageBitmap(bitmap);
但是这会在UI线程上加载图像,这可能会导致打嗝。最好是在不同的线程,例如使用:
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... params) {
try {
return loadBitmap(params[0]);
} catch (Exception e) {
Log.e("imagetask", "error loading bitmap", e);
return null;
}
}
protected Bitmap loadBitmap(String urlSpec) throws IOException {
InputStream is = new URL(urlSpec).openStream();
try {
return BitmapFactory.decodeStream(is);
} finally {
is.close();
}
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView iv = (ImageView) findViewById(R.id.myImage);
iv.setImageBitmap(bitmap);
}
}
}.execute("http://example.com/myimage.jpg");
我有这个代码运行没有错误,但图像从不显示。 imageview是空的。有什么想法吗? – 2011-05-03 16:54:11
@JJD,不是真的......有没有在LogCat中引起异常和/或可见的异常?我将为异常处理添加一些代码,我把它留下了。 – beetstra 2011-05-03 17:04:21
我需要在清单中添加Internet权限。谢谢! – 2011-05-03 17:10:39
- 1. 如何显示来自url的图像
- 2. 如何显示来自url的图像
- 3. Android - 如何在ListView中显示来自URL的图像?
- 4. 如何在Android中显示来自Url的图像?
- 5. 显示来自URL的图像Objective C
- 6. 来自URL的ListField显示图像
- 7. 显示来自JSON的GridView图像Android
- 8. Android:显示来自SDcard的图像
- 9. Android如何显示URL和图像
- 10. 在Android应用程序中显示来自URL的图像?
- 11. 如何显示来自JavaScript的图像
- 12. 如何显示来自FileReferenceList的图像?
- 13. 如何使用url显示来自文件夹的图像
- 14. 如何调整大小并显示来自url的图像?
- 15. 我如何显示来自url的图像?
- 16. 如何在Android中显示来自Uri的位图图像?
- 17. 如何在图像组件中显示来自URL的图像Appery
- 18. 如何显示来自特定目录的图像,android
- 19. 如何在Android中显示来自网络的图像
- 20. 启动意图查看器以显示来自url的图像
- 21. 来自URL的Android可绘制图像
- 22. 在图像视图中显示来自URL的图像显示模糊(不清晰)的图像?
- 23. 如何在android中的图库视图中显示来自web的图像
- 24. 如何显示来自摄像头的图像
- 25. 在uiimageview中显示来自url的图像
- 26. 在JADE中显示来自url的图像
- 27. 需要帮助显示来自url或filechooser的图像
- 28. 在ListView中显示来自url的可绘制图像
- 29. 检索并显示来自URL的多个图像
- 30. 无法在imageview中显示来自url的图像
可能重复的[如何在Android中显示互联网图像??](http://stackoverflow.com/questions/4223472/how从Android的互联网到显示图像) – Aleadam 2011-05-03 16:00:47