3

I am creating bitmap as follows

       ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), mSourceUri);
        try {
            bitmap = ImageDecoder.decodeBitmap(source));
        } catch (IOException e) {
            e.printStackTrace();
        }

This returns immutable bitmap. I saw google documentation and there is a method setMutableRequired() but I couldn't find how to use this method. It doesn't work on ImageDecoder as well as source

Ajeett
  • 826
  • 2
  • 6
  • 18
mayank1513
  • 8,767
  • 6
  • 37
  • 99

4 Answers4

3

Provide an ImageDecoder.OnHeaderDecodedListener as the second parameter to ImageDecoder.decodeBitmap().

Inside the listener you get the ImageDecoder, to which you can make desired changes.

ImageDecoder.decodeBitmap(imageSource, (decoder, info, source) -> {
    decoder.setMutableRequired(true);
});
Cliff
  • 51
  • 1
  • 6
3

From API 28

ImageDecoder.Source source = ImageDecoder.createSource(getContentResolver(), imageUri);
            ImageDecoder.OnHeaderDecodedListener listener = new ImageDecoder.OnHeaderDecodedListener() {
                @Override
                public void onHeaderDecoded(@NonNull ImageDecoder decoder, @NonNull ImageDecoder.ImageInfo info, @NonNull ImageDecoder.Source source) {
                    decoder.setMutableRequired(true);
                }
            };
            bitmap = ImageDecoder.decodeBitmap(source, listener);
Tarun konda
  • 1,500
  • 1
  • 10
  • 19
1

A bit prettier solution

imageBitmap = imageBitmap.copy(Bitmap.Config.ARGB_8888, true);

Refer this answer

mayank1513
  • 8,767
  • 6
  • 37
  • 99
  • 1
    There's nothing pretty about this solution - it makes a copy of a bitmap, doubling the memory required for a moment. setMutableRequired is a proper way without extra copy – Dimezis Apr 08 '21 at 15:29
0

Till the time a proper answer arrives to this question. Anyone with similar difficulty as mine can use BitmapFactory method to get mutable bitmap

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mSourceUri), null, options);

inspired from this answer.

mayank1513
  • 8,767
  • 6
  • 37
  • 99