How to save the image to SD card on button Click android [closed]

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

Leave a Comment