Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save bitmap image to specific location of gallery android 10

I am using this code:

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title" , "description");

and it is working well.

Problems:

  1. It is creating a folder called "Pictures" in gallery automatically. But I want different name, for example my app's name.
  2. insertImage() function of MediaStore is depreciated in android 10:

public static String insertImage (ContentResolver cr, String imagePath, String name, String description)

This method was deprecated in API level 29. inserting of images should be performed using MediaColumns#IS_PENDING, which offers richer control over lifecycle.

I have read the documentation and don't actually understand IS_PENDING and how to use it.

like image 417
Javlon Avatar asked Sep 07 '20 11:09

Javlon


People also ask

How do I save a picture on my Android Gallery?

From the text messaging inbox, tap the message containing the picture or video. Touch and hold the image. Select a save option (e.g., Save attachment, Save to SD card, etc.).

How do I save a bitmap image in Android 11?

To save the bitmap to Android storage, you could create a FileStream object with the path and then call the Bitmap. Compress method to generate the picture. Check the code: var folder = Android.

How do I save a picture to my gallery?

Right-click the illustration that you want to save as a separate image file, and then click Save as Picture. In the Save as type list, select the file format that you want.


1 Answers

Try this code :-

private void saveImage(Bitmap bitmap, @NonNull String name) throws IOException {
    boolean saved;
    OutputStream fos;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ContentResolver resolver = mContext.getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        fos = resolver.openOutputStream(imageUri);
    } else {
        String imagesDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;

        File file = new File(imagesDir);

        if (!file.exists()) {
            file.mkdir();
        }

        File image = new File(imagesDir, name + ".png");
        fos = new FileOutputStream(image);

    }

    saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
}
like image 107
Arjun saini Avatar answered Sep 19 '22 14:09

Arjun saini