Android用ImageView显示本地和网上的图片


知道路径就可以得到流, 得到流就可以得到bitmap  imageview.setImageBitmap(bitmap);

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

相关内容