LBugnion
LBugnion

Reputation: 6662

In Android, BitmapFactory.DecodeByteArray returns null for RGBA byte array

I am implementing a Xamarin Android application which does some image manipulation. I am loading a Bitmap, converting it to an RGBA byte array (4 bytes per pixel), and then I want to reconvert this byte array into a Bitmap.

Because of the nature of the pixel manipulation I am doing, I do NOT want to deal with JPEG or PNG compressed byte arrays. It has to be RGBA.

Here is some code which demonstrates my issue, reduced to the minimum:

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);

What is the way in Android to recreate a Bitmap from an RGBA byte array?

Complement of information: In iOS, I used CGBitmapContext with an RGB color space (CGColorSpace.CreateDeviceRGB()). In Windows 10, I used a WriteableBitmap. What's the equivalent in Android?

Thanks Laurent

Upvotes: 0

Views: 2180

Answers (2)

vidstige
vidstige

Reputation: 13085

You can just use Bitmap.copyPixels to write pixels from a buffer to a Bitmap, like so

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

Also as you already have a Bitmap there should be very little reason for you to copy it. If you really do need to copy it you can just do it like so

Bitmap bmp = Bitmap.createBitmap(bitmap);

The reason BitmapFactory.DecodeXXX does not work is because they expect an encoded image, while you have a pixel buffer that is not encoded. This is the opposite from what the functions expect. Instead use the example above.

Upvotes: 2

weston
weston

Reputation: 54801

Why doesn't this work?

BitmapFactory.DecodeByteArray and BitmapFactory.DecodeStream still requires all the headers of an image which copyPixelsToBuffer does not copy. Without these it can't tell the image encoding (bitmap, jpeg, png etc), or the width, height and bits per pixel.

The complimentary function to copyPixelsToBuffer is copyPixelsFromBuffer.

Upvotes: 0

Related Questions