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

首頁 > 系統 > Android > 正文

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

2019-12-12 02:47:13
字體:
來源:轉載
供稿:網友

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(); } 

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 始兴县| 广西| 始兴县| 涞源县| 寿宁县| 灵川县| 泸水县| 长岭县| 峨眉山市| 洞头县| 义乌市| 嘉义市| 宁化县| 固镇县| 江都市| 都江堰市| 汕尾市| 长宁县| 鱼台县| 广灵县| 徐汇区| 偏关县| 图们市| 姜堰市| 平江县| 乌兰浩特市| 南溪县| 兴义市| 太和县| 济阳县| 灵川县| 胶南市| 霍州市| 类乌齐县| 大宁县| 白河县| 南昌县| 邵阳市| 布拖县| 当阳市| 周至县|