在Android中,BitmapFactory.DecodeByteArray为RGBA字节数组返回null

时间:2015-07-12 07:49:06

标签: android bitmap bytearray

我正在实现一个Xamarin Android应用程序,它可以进行一些图像操作。我正在加载一个Bitmap,将其转换为RGBA字节数组(每个像素4个字节),然后我想将这个字节数组重新转换为Bitmap。

由于我正在进行像素处理的性质,我不想处理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颜色空间的CGBitmapContext(CGColorSpace.CreateDeviceRGB())。在Windows 10中,我使用了WriteableBitmap。什么是Android中的等价物?

由于 劳伦

2 个答案:

答案 0 :(得分: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不起作用的原因是因为他们期望编码图像,而您有一个编码的像素缓冲区。这与功能期望的相反。而是使用上面的例子。

答案 1 :(得分:0)

  

为什么这不起作用?

BitmapFactory.DecodeByteArrayBitmapFactory.DecodeStream仍然需要copyPixelsToBuffer不复制的图片的所有标头。没有它们就无法分辨图像编码(位图,jpeg,png等),或者每个像素的宽度,高度和位数。

copyPixelsToBuffer的免费功能是copyPixelsFromBuffer