如何将图像从其 URL 传输到 SD 卡? [英] How do I transfer an image from its URL to the SD card?

查看:39
本文介绍了如何将图像从其 URL 传输到 SD 卡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I save an images to the SD card that I retrieve from the image's URL?

推荐答案

首先,您必须确保您的应用程序具有写入 SD 卡的权限.为此,您需要在应用程序清单文件中添加使用权限写入外部存储.请参阅设置 Android 权限

First you must make sure your application has permission to write to the sdcard. To do this you need to add the uses permission write external storage in your applications manifest file. See Setting Android Permissions

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

Then you can you can download the URL to a file on the sdcard. A simple way is:

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

将权限放在清单中

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

这篇关于如何将图像从其 URL 传输到 SD 卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆