Skip to content

Instantly share code, notes, and snippets.

@andrespengineer
Last active April 14, 2021 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrespengineer/a0d2a873977d9e175ba4a8e49bb14d25 to your computer and use it in GitHub Desktop.
Save andrespengineer/a0d2a873977d9e175ba4a8e49bb14d25 to your computer and use it in GitHub Desktop.
Java Android save file
private static void saveBitmapAsNewFile(Bitmap target){
// Define directory names
String fileName = "new_file.jpg"; /* or Replace with yout filename*/
String root = "/my_images/";
OutputStream outputStream = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
ContentResolver resolver = getApplicationContext().getContentResolver();
ContentValues contentValues = new ContentValues(); // or your content values
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName); // avoid this column if DisplayName is already set
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + root);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
try {
resolver.notifyChange(Objects.requireNonNull(imageUri), null);
outputStream = resolver.openOutputStream(Objects.requireNonNull(imageUri));
} catch (FileNotFoundException e) {
e.printStackTrace();
LogUtil.e("Error in" + this.getClass().getName(), "=> Error creating directory on path " + imageUri);
}
}
else {
if (!isExternalStorageReadable() || !isExternalStorageWritable()) {
LogUtil.e("Error in" + this.getClass().getName(), "=> Cannot read or write on External directory ");
return;
}
String file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + root;
File dir = new File(file_path);
if (!dir.exists() && !dir.mkdirs()) {
LogUtil.e("Error in" + this.getClass().getName(), "=> Error creating directory on path " + file_path);
return;
}
File file = new File(dir, fileName);
if(file.exists())
return;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
try{
if(outputStream != null) {
target.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
LogUtil.e("Error in" + this.getClass().getName(), "=> Error creating image on path");
e.printStackTrace();
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment