ImageView 显示本地和网上的图片(转)

桃扇骨 2021-09-30 05:06 428阅读 0赞

Android用ImageView显示本地和服务器的图片(转)

ImageView是Android程序中经常用到的组件,它将一个图片显示到屏幕上。
在UI xml定义一个ImageView如下:

  1. public void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.myimage);
  4. ImageView image1 = (ImageView) findViewById(R.myImage.image);
  5. //Bitmap bitmap = getLoacalBitmap("/aa/aa.jpg"); //从本地取图片
  6. Bitmap bitmap =
  7. getHttpBitmap("http://blog.3gstdy.com/wp-content/themes/twentyten/images/headers/path.jpg");
  8. //从网上取图片
  9. image1 .setImageBitmap(bitmap); //设置Bitmap
  10. }
  11. /**
  12. * 加载本地图片
  13. * http://bbs.3gstdy.com
  14. * @param url
  15. * @return
  16. */
  17. public static Bitmap getLoacalBitmap(String url) {
  18. try {
  19. FileInputStream fis = new FileInputStream(url);
  20. return BitmapFactory.decodeStream(fis);
  21. } catch (FileNotFoundException e) {
  22. e.printStackTrace();
  23. return null;
  24. }
  25. }
  26. /**
  27. * 从服务器取图片
  28. *http://bbs.3gstdy.com
  29. * @param url
  30. * @return
  31. */
  32. public static Bitmap getHttpBitmap(String url) {
  33. URL myFileUrl = null;
  34. Bitmap bitmap = null;
  35. try {
  36. Log.d(TAG, url);
  37. myFileUrl = new URL(url);
  38. } catch (MalformedURLException e) {
  39. e.printStackTrace();
  40. }
  41. try {
  42. HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
  43. conn.setConnectTimeout(0);
  44. conn.setDoInput(true);
  45. conn.connect();
  46. InputStream is = conn.getInputStream();
  47. bitmap = BitmapFactory.decodeStream(is);
  48. is.close();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. return bitmap;
  53. }

转载于:https://www.cnblogs.com/896240130Master/p/6800567.html

发表评论

表情:
评论列表 (有 0 条评论,428人围观)

还没有评论,来说两句吧...

相关阅读