2012-04-05 120 views
1

我需要從網上獲取圖像並將其存儲在手機中供以後使用。從網上獲取圖像並將其保存到手機內存?

我tryed這一點:

public Drawable grabImageFromUrl(String url) throws Exception 
    { 
    return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src"); 
    } 

所以這我的函數從網址抓取圖像,我只需要下面的一個進程得到返回的繪製和保存。

我該怎麼做?

+0

你想只下載一個文件或多個文件? – 2012-04-05 13:59:55

回答

3

基於here,您實際上可以使用不同的方法下載圖像。在保存之前將它作爲drawable存儲是否絕對有必要?因爲我認爲你可以先保存它,然後打開它,如果需要的話。

URL url = new URL ("file://some/path/anImage.png"); 
InputStream input = url.openStream(); 
try { 
    //The sdcard directory e.g. '/sdcard' can be used directly, or 
    //more safely abstracted with getExternalStorageDirectory() 
    String storagePath = Environment.getExternalStorageDirectory(); 
    OutputStream output = new FileOutputStream (storagePath + "/myImage.png"); 
    try { 
     byte[] buffer = new byte[aReasonableSize]; 
     int bytesRead = 0; 
     while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
      output.write(buffer, 0, bytesRead); 
     } 
    } finally { 
     output.close(); 
    } 
} finally { 
    input.close(); 
} 
相關問題