2011-09-09 38 views
31

我想從一個字節數組創建一個位圖。從android中的byteArray創建位圖

我試着下面的代碼

Bitmap bmp; 

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

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

但是,當我特林與位圖初始化Canvas對象像

Canvas canvas = new Canvas(bmp); 

這導致了錯誤

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

然後如何從byteArray中獲取可變位圖。

在此先感謝。

回答

58

您需要一個可變的Bitmap才能創建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 

編輯:正如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); // now it should work ok 
+0

感謝它的工作 – surendra

+1

是不是Bitmap.copy()完全創建一個新的數組?這似乎是對記憶的浪費。我很想知道如何直接獲取可變的位圖。 –

+0

不幸的是,我不知道任何其他方式來獲得一個可變的位圖(至少從一個'ByteArray')。 –