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
  • 814
  • 2
  • 7
  • 18
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122

4 Answers4

4

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
  • 61
  • 1
  • 6
4

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,740
  • 1
  • 11
  • 19
2

A bit prettier solution

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

Refer this answer

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
  • 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
  • @Dimezis and how you can get it from video memory without copyng? – Alexufo Jun 16 '23 at 12:06
  • 1
    @Alexufo with `setMutableRequired` the returned bitmap will be software-allocated https://developer.android.com/reference/android/graphics/ImageDecoder#ALLOCATOR_DEFAULT – Dimezis Jun 16 '23 at 14:16
  • @Dimezis thx! You are right!!! – Alexufo Jun 16 '23 at 20:00
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.

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122