Aiiz Cabuhat Ü
Aiiz Cabuhat Ü

Reputation: 149

How to download image in android?

I have an image to the right and a button "download" to the left. the image is from my drawable. now,when i try to click the download i want to put the image to my sdcard downloads. Please help me i only see about download in url. is there other solution for this . Thanks

public class ImageDownloader {

public void download(String url, ImageView imageView) {
        BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
        task.execute(url);
    }
}

 /* class BitmapDownloaderTask, see below */
}

Upvotes: 1

Views: 1441

Answers (1)

Tushar Gogna
Tushar Gogna

Reputation: 5083

First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:

 BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

Then you must get to directory (a File object) from SD Card such as:

File sdCardDirectory = Environment.getExternalStorageDirectory();

Next, create your specific file for image storage:

 File image = new File(sdCardDirectory, "test.png");

After that, you just have to write the Bitmap such as:

boolean success = false;

// Encode the file as a PNG image.
FileOutputStream outStream;
try {

    outStream = new FileOutputStream(image);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
    /* 100 to keep full quality of the image */

    outStream.flush();
    outStream.close();
    success = true;
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Finally, just deal with the boolean result if needed. Such as:

if (success) {
    Toast.makeText(getApplicationContext(), "Image saved with success",
            Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(getApplicationContext(),
            "Error during image saving", Toast.LENGTH_LONG).show();
}

Don't forget to add the following permission in your Manifest:

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

Upvotes: 1

Related Questions