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

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

问题描述

如何将图像保存到从图像网址中检索到的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();
}

编辑:
将权限清单

EDIT : Put permission in manifest

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

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

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