android - 如何将图像从其 URL 传输到 SD 卡?

标签 android image download android-sdcard

如何将图像保存到从图像 URL 检索到的 SD 卡中?

最佳答案

首先,您必须确保您的应用程序具有写入 sdcard 的权限。为此,您需要在应用程序 list 文件中添加使用权限write external storage。见 Setting Android Permissions

然后您可以将 URL 下载到 sdcard 上的文件中。一个简单的方法是:

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()
    File storagePath = Environment.getExternalStorageDirectory();
    OutputStream output = new FileOutputStream (new File(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();
}

编辑: 在 list 中添加权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

关于android - 如何将图像从其 URL 传输到 SD 卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3296850/

相关文章:

android - 错误 :(24, 11) 无法解析 : com. android.support :appcompat-v7:8. 0.+

python - dlib/cv2 处理数十万张图片

http - 使用GZIP压缩下载文件时出现"Content decoding has failed"错误

c# - 在仍在下载的同时播放媒体文件(Windows Phone)

icons - 我可以为下载的 url 文件使用自定义 Logo 吗?

java - 将字符串转换为 JSON 数组

java - GoogleSignIn 有效,但 Google_DEFAULT_GAMES 无效

android - 运行应用程序但不从启动器运行

image - SSRS : Report loading external images, 找不到图片,可以隐藏图片控件吗

wpf - 使用 XAML 图像作为 WPF 窗口背景