Quantcast
Channel: Coding and Programing » image
Viewing all articles
Browse latest Browse all 10

transfer image from its URL to SD card

$
0
0

Problem And Question

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

Best Solution And Answer

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

Viewing all articles
Browse latest Browse all 10

Trending Articles