8
votes

I am using an Imageview and a Button in 1 XML, and I am retriving the images as URL from webServer and displaying it on the ImageView. Now if the Button(Save) is clicked I need to save that particular image into SD card. How to do this?

NOTE: Present Image Should be saved.

2
There are a lot of answers to your question, use search first! stackoverflow.com/questions/4875114/…Dmytro Danylyk

2 Answers

52
votes

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) mImageView1.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 thanks to its method compress 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"/>
5
votes

Probable Solution is

Android - Saving a downloaded image from URL onto SD card

Bitmap bitMapImg;
void saveImage() {
        File filename;
        try {
            String path = Environment.getExternalStorageDirectory().toString();

            new File(path + "/folder/subfolder").mkdirs();
            filename = new File(path + "/folder/subfolder/image.jpg");

            FileOutputStream out = new FileOutputStream(filename);

            bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

            MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName());

            Toast.makeText(getApplicationContext(), "File is Saved in  " + filename, 1000).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }