Last active
September 5, 2021 16:27
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And from Activity/Fragment/Anywhere simply call :
where,
The below code is optional:
Use it^ whenever you need to refresh gallery So that when image is saved it can be viewed in gallery immediately