从ByteArray进行机器人创建位图位图、机器人、ByteArray

2023-09-13 23:42:37 作者:久腻°

我想创建一个ByteArray的位图。

I want to create a bitmap from a bytearray .

我尝试以下codeS

I tried the following codes

Bitmap bmp;

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

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

不过,当我特林初始化Canvas对象与像

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.

在此先感谢。

推荐答案

您需要一个可变的位图,以创建画布

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

Bitmap bmp;
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

编辑:正如诺亚塞德曼说,你可以做到这一点,而无需创建一个副本

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

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