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

Jameskittu picture Jameskittu · Jul 21, 2010 · Viewed 38k times · Source

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

Answer

Akusete picture Akusete · Jul 21, 2010

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

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