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

24

我如何将从图像URL获取的图像保存到SD卡中?


@Akusete... 你应该将 output.write(buffer, 0, buffer.length); 中的 'buffer.length' 替换为 bytesRead。否则会在文件末尾附加垃圾数据。 - shaffooo
2个回答

47

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

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

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" />

1
@Paresh:谢谢,我已经更新了代码,使用getExternalStorageDirectory()。你知道它返回一个尾随斜杠吗?例如/sdcard/sdcard/ - Akusete
1
你的问题是无意义的,因为Environment.getExternalStorageDirectory()不返回一个字符串,因此你的代码无法编译。我已经为你纠正了代码。 - Jeff Axelrod
2
aReasonableSize是一个不会导致内存溢出异常的大小。通常1024或2048就足够了。 - Lazy Ninja

8

关于提高性能的多线程技术,可以在 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;
}

4
这并没有说明如何将图像保存到SD卡中,只是说明如何将图像下载到内存中。 - Jeff Axelrod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接