Skip to content

Instantly share code, notes, and snippets.

@johnsage25
Forked from vxhviet/saveToExternalStorage.md
Created November 21, 2022 21:51
Show Gist options
  • Save johnsage25/e5707f3693f32dc670451ce4b113b9dd to your computer and use it in GitHub Desktop.
Save johnsage25/e5707f3693f32dc670451ce4b113b9dd to your computer and use it in GitHub Desktop.
Android saving Bitmap to external storage.

Source: StackOverflow

Question: How do I save Bitmap to extrenal storage in Android?

Answer:

Use this function to save your bitmap in SD card:

public void saveTempBitmap(Bitmap bitmap) {
        if (isExternalStorageWritable()) {
            saveImage(bitmap);
        }else{
        //prompt the user or do something
        }
    }

    private void saveImage(Bitmap finalBitmap) {

        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fname = "Shutta_"+ timeStamp +".jpg";

        File file = new File(myDir, fname);
        if (file.exists()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

and add this in manifest

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

EDIT: By using this line you can able to see saved images in the gallery view. [UNTESTED]

sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));

look at this link also http://rajareddypolam.wordpress.com/?p=3&preview=true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment