欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android讀取服務(wù)器圖片的三種方法

 更新時(shí)間:2017年05月31日 08:39:54   作者:wanghualei2  
這篇文章主要為大家詳細(xì)介紹了Android讀取服務(wù)器圖片的三種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

Android鏈接服務(wù)器獲取圖片在此提供三種方法,已通過驗(yàn)證,無誤。

方法一:

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的輸入流中獲取數(shù)據(jù)將其轉(zhuǎn)化為Bitmap型數(shù)據(jù)。

在功能代碼中:

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);  // 關(guān)鍵是這句代 
  } catch (Exception e) { 
    e.printStackTrace(); 
  } 
  return pic; 
} 

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

第三種方法:

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

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

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

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

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

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論