Skip to content

Instantly share code, notes, and snippets.

@jaikeerthick
Last active September 5, 2021 16:27
Show Gist options
  • Save jaikeerthick/594ccee10b1831832b77a3bdbe903ab9 to your computer and use it in GitHub Desktop.
Save jaikeerthick/594ccee10b1831832b77a3bdbe903ab9 to your computer and use it in GitHub Desktop.
Helper class to save images of type Bitmap to storage (Assumed that storage permission is already allowed)
public class ImageSaver {
public static void saveImage( Context context, String FILE_NAME, Bitmap bitmap){
String savedImagePath = null;
final File path = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DCIM + "/YOUR_DIRECTORY_NAME/");
savedImagePath = path.getAbsolutePath();
// check if already exists
if(!path.exists()) path.mkdirs();
final File file = new File(path, FILE_NAME + ".jpg");
try
{
final FileOutputStream FOStream = new FileOutputStream(file);
final BufferedOutputStream BOStream = new BufferedOutputStream(FOStream, 8192);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, BOStream);
BOStream.flush();
BOStream.close();
}
catch (final IOException e) {e.printStackTrace();}
// add & refresh the system gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(savedImagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
}
@jaikeerthick
Copy link
Author

jaikeerthick commented Sep 4, 2021

And from Activity/Fragment/Anywhere simply call :

ImageSaver.save(context, filename, resource)

where,

 context : Context
 filename : String
 resource : Bitmap

The below code is optional:

// add & refresh the system gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(savedImagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);

Use it^ whenever you need to refresh gallery So that when image is saved it can be viewed in gallery immediately

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