Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

canvas - create Bitmap from byteArray in android

I want to create a bitmap from a bytearray .

I tried the following codes

Bitmap bmp;

bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

and

ByteArrayInputStream bytes = new ByteArrayInputStream(data); 
BitmapDrawable bmd = new BitmapDrawable(bytes); 
bmp = bmd.getBitmap(); 

But ,When i am tring to initialize the Canvas object with the bitmap like

Canvas canvas = new Canvas(bmp);

It leads to an error

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

Then how to get a mutable bitmap from an byteArray.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need a mutable Bitmap in order to create the Canvas.

Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap); // now it should work ok

Edit: As Noah Seidman said, you can do it without creating a copy.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options);
Canvas canvas = new Canvas(bmp); // now it should work ok

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...