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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3296850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:33:43  来源:igfitidea点击:

How do I transfer an image from its URL to the SD card?

androidimagedownloadandroid-sdcard

提问by Jameskittu

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

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

回答by Akusete

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 storagein your applications manifest file. See Setting Android Permissions

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

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

然后,您可以将 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();
}

EDIT :Put permission in manifest

编辑:将权限放在清单中

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

回答by ognian

An excellent example can be found in the latest poston Android developer's blog:

一个很好的例子可以在 Android 开发者博客的最新文章中找到:

static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) { 
            Log.w("ImageDownloader", "Error " + statusCode + 
               " while retrieving bitmap from " + url); 
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent(); 
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();  
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or
        // IllegalStateException
        getRequest.abort();
        Log.w("ImageDownloader", "Error while retrieving bitmap from " + url,
           e.toString());
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}