2012-04-05 65 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(); 
} 
相关问题