Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a resource to a mutable bitmap

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?

like image 904
stealthcopter Avatar asked Sep 11 '10 23:09

stealthcopter


People also ask

How do you make a bitmap mutable?

Options options = new BitmapFactory. Options(); options. inMutable=true; myBitmap=BitmapFactory. decodeFile(filePath,options);

How do I create a bitmap from resources?

To create a bitmap from a resource, you use the BitmapFactory method decodeResource(): Bitmap bitmap = BitmapFactory. decodeResource(getResources(), R. drawable.


3 Answers

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

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

like image 91
KNfLrPn Avatar answered Nov 02 '22 10:11

KNfLrPn


There are several ways to create a copy of it. This thread might help you: http://www.anddev.org/how_to_modify_the_image_file-t513.html

like image 34
Moss Avatar answered Nov 02 '22 10:11

Moss


You'd better use RapidDecoder.

import rapid.decoder.BitmapDecoder;

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

Works for API level 8.

like image 42
suckgamony Avatar answered Nov 02 '22 10:11

suckgamony