Android 从网络获取图像并将其保存到手机内存?

Android 从网络获取图像并将其保存到手机内存?,android,url,android-file,android-image,Android,Url,Android File,Android Image,我需要从网络上获取图像,并将其存储在手机中以备日后使用 我试着这样做: public Drawable grabImageFromUrl(String url) throws Exception { return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src"); } 所以这是我从Url抓取图像的函数,我只需要一个过程来获取返回的drawable并保存 我该怎么做呢?基于

我需要从网络上获取图像,并将其存储在手机中以备日后使用

我试着这样做:

 public Drawable grabImageFromUrl(String url) throws Exception
    {
     return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src");
    }
所以这是我从Url抓取图像的函数,我只需要一个过程来获取返回的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();
}
基于此,您实际上可以使用不同的方法下载图像。在保存之前,是否绝对有必要将其存储为可提取文件?因为我认为你可以先保存它,然后打开它,如果需要的话

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

请参见此处给出的完整示例


请参见此处给出的完整示例


是否只下载一个或多个文件?是否只下载一个或多个文件?