0

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

Andrew Simpson
  • 6,145
  • 9
  • 59
  • 153
  • 1
    Sorry what's the question ? Please edit. – AceKing Aug 26 '19 at 09:11
  • @AceKing What do you mean what is the question?? – Andrew Simpson Aug 26 '19 at 09:12
  • usually, OP contains a question. You asked none of it. – AceKing Aug 26 '19 at 09:12
  • 1
    You copy PNG bytes (which are compressed, encoded pixel data) into pixel bytes. What is your ultimate goal, why are you doing this? – CodeCaster Aug 26 '19 at 09:13
  • @CodeCaster I receive images in byte array format from a udp connection. I want to save that byte array into an image, I do not need to test the udp. The result is the same as above – Andrew Simpson Aug 26 '19 at 09:15
  • 1
    Then create a bitmap from that byte array, specifying the pixel format, so it gets decoded properly. – CodeCaster Aug 26 '19 at 09:16
  • @CodeCaster I think I see what you are saying now. The issue I had with using memorystream was that on the Raspberry Pi it cause a memory issue (not on the desktop) and I was looking at alternatives to load the byte array (which is an mjpeg) into an image – Andrew Simpson Aug 26 '19 at 09:18
  • @AndrewSimpson If the issue is caused by unclosed streams, you should use a `using` block for the stream, create the image in there, and then hard-clone that image (either using `LockBits` and `Marshal.Copy` as above, or by using the `new Bitmap(bitmap)` constructor) before the end of the `using` block. – Nyerguds Sep 16 '19 at 09:42

0 Answers0