Home > database >  How to save a bitmap on storage in Android Q and later?
How to save a bitmap on storage in Android Q and later?

Time:04-09

In my application, I have to store a bitmap as a PNG file in shared memory, to make it visible for Gallery app. First, I tried to store the image in /Android/data/package.name/files/Pictures. I got this path from context.getExternalFilesDir(Environment.DIRECTORY_PICTURES). Images stored in this directory are not detected by Gallery. Then I read a few articles and SO posts about MediaStore and I tried to save my image with it.

This is a function that I use to store bitmap. It does not throw any exception, returns true, bitmap.compress() also returns true but I can't find any PNG image in device's memory. I tried to look for it using Gallery and file manager. I also tried to change it to save JPEG instead of PNG but it also does not work.

Could you help me to figure out why this function does not save image to device's store?

I tested it on Samsung A52s 5G, Android 12, OneUI 4.0.

private boolean saveImageToStorageAndroidQ(Bitmap bitmap, String filename) {
    filename = filename   ".png";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
    values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

    final ContentResolver resolver = getActivity().getContentResolver();
    final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    Uri uri = resolver.insert(contentUri, values);

    try {
        OutputStream imageOutStream = resolver.openOutputStream(uri);
        bitmap.compress(Bitmap.CompressFormat.PNG, 95, imageOutStream);
        imageOutStream.flush();
        imageOutStream.close();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (uri != null)
            resolver.delete(uri, null, null);
    }
}

CodePudding user response:

You can also use this method. Thought it's long, it's better as the other one has been deprecated. Use this code:

String filename = "pippo.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);

try {
     FileOutputStream out = new FileOutputStream(dest);
     bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
     out.flush();
     out.close();
} catch (Exception e) {
     e.printStackTrace();
}

CodePudding user response:

You can use a very easy method:

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, filename, "Description");

This is deprecated. Try this answer

  • Related