0

I'm trying to create a canvas from a PNG file that I have loaded into a bitmap, but it gives an error. Here's the code:

public Bitmap CABINET_Bitmap;

AssetManager assetManager = this.getAssets();
inputStream = assetManager.open("background.png");
CABINET_Bitmap = BitmapFactory.decodeStream(inputStream);

// Next line gives error
Canvas cv = new Canvas(CABINET_Bitmap);

If I create the bitmap, rather than load it in, by doing:

CABINET_Bitmap = Bitmap.createBitmap(480, 640, Config.RGB_565);
Canvas cv = new Canvas(CABINET_Bitmap);

Then the canvas creation works. Any ideas what I'm doing wrong?

Benoit
  • 1,995
  • 1
  • 13
  • 18

1 Answers1

0

The documentation states:

Construct a canvas with the specified bitmap to draw into. The bitmap must be mutable.

The initial target density of the canvas is the same as the given bitmap's density.

So what I'm assuming is BitmapFactory.decodeStream() is returning an immutable bitmap while Bitmap.createBitmap() is return a mutable one. Instead, use BitmapFactory.Options and set inMutable to true.

BitmapFactory.Options o = new BitmapFactory.Options();
o.inMutable = true;
CABINET_Bitmap = BitmapFactory.decodeStream(inputStream, o);
Canvas cv = new Canvas(CABINET_Bitmap);

See if that works.

DeeV
  • 35,865
  • 9
  • 108
  • 95
  • Sounds great! Unfortunately, though my intellisense shows me an "inMutable" property, when I run the line "o.inMutable = true;" I get an error: NoSuchFieldError... – user1358999 Aug 09 '12 at 14:47
  • D'oh. I just noticed it was added in API 11. Well, I'm pretty sure that it's the problem. Thus, you need to convert the bitmap from immutable to mutable. http://www.anddev.org/how_to_modify_the_image_file-t513.html and http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource-returns-a-mutable-bitmap-in-android-2-2-and-an-immu seem to be good places to start. I hope that helps. – DeeV Aug 09 '12 at 14:51
  • Brilliant, I should be able to fix it then. Thanks for your help. Saved me several hours of banging my head against the desk. – user1358999 Aug 09 '12 at 14:56