-1

I have learnt how to export pixel data of an image to byte array, here is my code

void Button2Click(object sender, EventArgs e)
{
    Bitmap img = new Bitmap (@"24x30.bmp");
    var BitmapData = img.LockBits( new Rectangle(0,0,img.Width,img.Height),ImageLockMode.ReadOnly,img.PixelFormat);
    var length = BitmapData.Stride * BitmapData.Height;
    MessageBox.Show(BitmapData.Width.ToString());
    byte[] bytes = new byte[length];
    Marshal.Copy(BitmapData.Scan0, bytes, 0, length);
    img.UnlockBits(BitmapData);
    string test = ByteArrayToBinary(bytes);
}

I convert the bytes to string bit but lets ignore it. What I want to know is, how can I convert the byte of pixel data to an image? Please share the code and the reference.

I have read many references but I don't get it until now.

EDIT:

This summary of my case, i have Stride, Width, Height, and Byte[] of Pixel data. How can i reconstruct it to image again thanks

Jackuze
  • 1
  • 1

2 Answers2

1

Same code, but copy the other way. (You can read a dummy image or use another image constructor.)

0

Obviously, you first step should be to somehow convert your text back to a byte array, but then you'll see that you can't actually create an image from just that data.

As you mentioned in comments already, your dumped binary block is missing all header data. You need the original width, height and pixel format before you can convert the data back to an image.

Also, if this is an indexed image, there will be a colour palette, and you don't save that either.

And finally, you copy all data in the image memory. Images are kept in memory per line of pixels, but these lines are usually rounded to the next multiple of four bytes (except in some indexed pixel formats, I think). This means that unless your image uses four bytes per pixel (32 bits per pixel), the bytes you end up with may contain junk data at the end of each line. You don't trim that off in any way, meaning you not only need the width and height, but the stride as well, before you can reconstruct the image.

As for how to build the image, the method is pretty much the same. You make a new image with the correct dimensions and pixel format, open its backing memory using LockBits but in WriteOnly mode, and copy your data into it.

I posted a full method for that on this site before, so feel free to check it out.

Nyerguds
  • 5,360
  • 1
  • 31
  • 63