2015-07-12 305 views
0

我正在實現一個Xamarin Android應用程序,它執行一些圖像操作。我加載一個位圖,將其轉換爲RGBA字節數組(每像素4個字節),然後我想將這個字節數組重新轉換爲位圖。在Android中,BitmapFactory.DecodeByteArray爲RGBA字節數組返回null

由於我在做像素操作的本質,我不想處理JPEG或PNG壓縮字節數組。它必須是RGBA。

下面是一些代碼,演示了我的問題,減少到最低限度:

var size = bitmap.Height * bitmap.RowBytes; 
var buffer = ByteBuffer.Allocate(size); 
bitmap.CopyPixelsToBuffer(buffer); 

buffer.Rewind(); 

var bytes = new byte[size]; 
buffer.Get(bytes, 0, bytes.Length); 

// At this point, bytes is an RGBA byte array, and I verified 
// that the bytes are consistent with the image. 

// Why doesn't this work? 
var bitmap1 = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length); 

// Or this? 
var imageStream = new MemoryStream(bytes); 
var bitmap2 = BitmapFactory.DecodeStream(imageStream); 

什麼是Android的方式來重新從RGBA字節數組位圖?

補充信息:在iOS中,我使用了RGB顏色空間(CGColorSpace.CreateDeviceRGB())的CGBitmapContext。在Windows 10中,我使用了一個WriteableBitmap。 Android中有什麼等價物?

感謝 洛朗

回答

2

你可以使用Bitmap.copyPixels寫從緩衝區像素爲Bitmap,像這樣

Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
bmp.copyPixelsFromBuffer(buffer); 

而且你已經Bitmap應該有非常少的原因爲你複製它。如果你確實需要複製它,你可以做它像這樣

Bitmap bmp = Bitmap.createBitmap(bitmap); 

原因BitmapFactory.DecodeXXX不工作是因爲他們預期編碼圖像,當你有一個像素緩衝區是編碼。這與功能所期望的相反。請使用上面的示例。

0

爲什麼不能正常工作?

BitmapFactory.DecodeByteArrayBitmapFactory.DecodeStream仍然需要這copyPixelsToBuffer不會複製圖像的所有頭。沒有這些,它不能告訴圖像編碼(位圖,jpeg,png等),或者每個像素的寬度,高度和位數。

copyPixelsToBuffer的免費功能是copyPixelsFromBuffer