Image from byte array creating bad image when using Marshalling

36 Views Asked by At

I am trying to convert a byte array to an image. For testing I start with this image:

enter image description here

I then load it into a byte array:

byte[] imageData = File.ReadAllBytes("download.png");

I then create new bitmap to 'deposit' this byte array into:

Bitmap bmp = new Bitmap(704, 480, PixelFormat.Format24bppRgb);

n.b. the height and width are the same as the original image.

I then create a BitmapData and lock all pixels to be written:

BitmapData bmpData = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                ImageLockMode.ReadWrite, bmp.PixelFormat);

I then copy the data from the byte array into BitmapData.Scan0:

Marshal.Copy(imageData, 0, bmpData.Scan0, imageData.Length);

I then unlock the pixels:

bmp.UnlockBits(bmpData);

I then finally save it to a file:

bmp.Save("D:\\test.png");

That saved file looks like this:

enter image description here

0

There are 0 best solutions below