Loading a resource to a mutable bitmap
Asked Answered
A

3

25

I am loading a bitmap from a resource like so:

 Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image);

What I want to do is make some changes to the bitmap before It gets drawn to the main canvas in my draw method (As it would seem wasteful to repeat lots of drawing in my main loop when it isn't going to change). I am making the changes to the bitmap with the following:

Canvas c = new Canvas(mBackground);
c.drawARGB(...); // etc

So naturally I get an exception

java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor

So to avoid that I made a copy of the bitmap so that it is mutable

Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image).copy(Bitmap.Config.ARGB_8888, true);

Which avoid the problem however it sometimes causes OutOfMemoryExceptions, do know any better ways of achieving what I want?

Atul answered 11/9, 2010 at 23:13 Comment(1)
in case you need to handle all API levels, check out this post: https://mcmap.net/q/176626/-bitmapfactory-decoderesource-returns-a-mutable-bitmap-in-android-2-2-and-an-immutable-bitmap-in-android-1-6Dislocate
R
24

Use decodeResource(Resources res, int id, BitmapFactory.Options opts) and specify inMutable in the options.

http://developer.android.com/reference/android/graphics/BitmapFactory.html

Rip answered 19/10, 2011 at 3:44 Comment(2)
Works, but needs at least API level 11.Juggler
I can confirm, that the API level is a problem there:(Bootlace
S
1

You'd better use RapidDecoder.

import rapid.decoder.BitmapDecoder;

Bitmap mBackground = BitmapDecoder.from(res, R.drawable.image)
        .mutable().decode();

Works for API level 8.

Sallee answered 5/1, 2014 at 9:1 Comment(0)
E
0

Instad of yours:

Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image);

Use:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;

Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image, options);
Emblazonry answered 12/9, 2019 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.