国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android讀取服務器圖片的三種方法

2019-10-23 18:27:38
字體:
來源:轉載
供稿:網友

Android鏈接服務器獲取圖片在此提供三種方法,已通過驗證,無誤。

方法一:

public static Bitmap getImage(String path){      try {     HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();     conn.setConnectTimeout(5000);     conn.setRequestMethod("GET");     System.out.println("tdw1");     if(conn.getResponseCode() == 200){       InputStream inputStream = conn.getInputStream();       Bitmap bitmap = BitmapFactory.decodeStream(inputStream);         return bitmap;     }   } catch (Exception e) {     e.printStackTrace();   }   return null; } 

在第一種方法中,從conn的輸入流中獲取數據將其轉化為Bitmap型數據。

在功能代碼中:

image.setImageBitmap(getImage("路徑")); 

image為ImageView型控件。

第二種方法:

public static Bitmap getImage1(String path){        HttpGet get = new HttpGet(path);     HttpClient client = new DefaultHttpClient();     Bitmap pic = null;      try {       HttpResponse response = client.execute(get);       HttpEntity entity = response.getEntity();       InputStream is = entity.getContent();        pic = BitmapFactory.decodeStream(is);  // 關鍵是這句代   } catch (Exception e) {     e.printStackTrace();   }   return pic; } 

這個方法類似上面那個方法。在功能代碼中設置是一樣的

第三種方法:

public static Uri getImage2(String path,File cacheDir){     File localFile = new File(cacheDir,MD5.getMD5(path)+path.substring(path.lastIndexOf(".")));     if(localFile.exists()){       return Uri.fromFile(localFile);     }else     {       HttpURLConnection conn;       try {         conn = (HttpURLConnection) new URL(path).openConnection();         conn.setConnectTimeout(5000);         conn.setRequestMethod("GET");         if(conn.getResponseCode() == 200){           System.out.println("tdw");           FileOutputStream outputStream = new FileOutputStream(localFile);           InputStream inputStream = conn.getInputStream();           byte[] buffer = new byte[1024];           int length = 0;           while((length=inputStream.read(buffer))!=-1){             outputStream.write(buffer, 0, length);           }           inputStream.close();           outputStream.close();           return Uri.fromFile(localFile);         }       } catch (Exception e) {         // TODO Auto-generated catch block         e.printStackTrace();       }     }     return null;     } 

第三種方法,將從服務器獲取的數據存入本地的文件中,如果文件已存在,則不需要從服務器重新獲取數據。
在功能代碼中:

image.setImageURI(getImage2(path, cache)); 

上面代碼中設置圖片為緩存設置,這樣如果圖片資源更新了,則需要重新命名文件的名字,這樣才能夠重新加載新圖片。

cache = new File(Environment.getExternalStorageDirectory(),"cache"); if(!cache.exists()){   cache.mkdirs(); } 

這里是設置 緩存圖片的路徑。
以上為三種方法。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 舒兰市| 海盐县| 二连浩特市| 古丈县| 时尚| 文成县| 潜山县| 河南省| 万全县| 磐安县| 浦城县| 洛阳市| 威信县| 灵山县| 黎川县| 宁阳县| 顺昌县| 南投县| 太谷县| 清丰县| 顺义区| 珠海市| 财经| 岫岩| 泰安市| 百色市| 枝江市| 永靖县| 前郭尔| 垣曲县| 皮山县| 屯门区| 临夏市| 吴旗县| 永平县| 龙海市| 黔东| 杨浦区| 筠连县| 石河子市| 英吉沙县|