我如何从它的URL传送一个图像到SD卡? [英] How do I transfer an image from its URL to the SD card?

查看:188
本文介绍了我如何从它的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

然后你可以,你可以将网址下载到的SD卡的文件。一个简单的方法是:

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天全站免登陆