从android中的byteArray创建位图 [英] create Bitmap from byteArray in android

查看:156
本文介绍了从android中的byteArray创建位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从bytearray创建一个位图。



我试过下面的代码

  Bitmap bmp; 

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

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

但是,当我使用像

$ b这样的位图初始化Canvas对象
$ b

 画布canvas = new Canvas(bmp); 

这会导致错误

  java.lang.IllegalStateException:传递给Canvas构造函数的不可变位图

如何从byteArray获取可变位图。



提前感谢。

解决方案>

您需要一个可变的位图才能创建 Canvas

 位图bmp = BitmapFactory.decodeByteArray(data,0,data.length); 
Bitmap mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888,true);
Canvas canvas = new Canvas(mutableBitmap); //现在应该可以正常工作了

编辑:正如Noah Seidman所说,

  BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inMutable = true;
Bitmap bmp = BitmapFactory.decodeByteArray(data,0,data.length,options);
Canvas canvas = new Canvas(bmp); //现在应该工作确定


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.

解决方案

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

这篇关于从android中的byteArray创建位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆