Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18548

How to get mutable bitmap using ImageDecoder?

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

Upvotes: 3

Views: 1584

Answers (4)

Tarun konda
Tarun konda

Reputation: 1880

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);

Upvotes: 5

Cliff
Cliff

Reputation: 61

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);
});

Upvotes: 4

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18548

A bit prettier solution

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

Refer this answer

Upvotes: 1

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18548

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.

Upvotes: 0

Related Questions