C# – How to create an image from a 2-dimensional byte array


In my project after long process, i got a 2 dimensional byte array from the IR camera.

The byte array holds image in it…

How to convert that byte array to image in C#..

I know that by

MemoryStream ms = new MemoryStream(byteArray);
System.drawing.Image im = Image.FromStream(ms);

We can pass 1 dimensional array and convert it into image..

If i pass 2 dimensional array as a single dimensional array.. it shows error..

How to rectify it..???? or else how to convert 2 dimensional byte array to image…???

Thank you!!

Best Solution

If it's a rectangular array (i.e. a byte[,]) instead of a jagged array (byte[][]) then you may be able to do it pretty simply with some unsafe code.

Have a look at my parallel Mandelbrot set generation code - only the bottom bit is interesting, where it constructs a Bitmap from a palette and a block of data:

byte[] data = query.ToArray();

    fixed (byte* ptr = data)
        IntPtr scan0 = new IntPtr(ptr);
        Bitmap bitmap = new Bitmap(ImageWidth, ImageHeight, // Image size
                                   ImageWidth, // Scan size
                                   PixelFormat.Format8bppIndexed, scan0);
        ColorPalette palette = bitmap.Palette;
        palette.Entries[0] = Color.Black;
        for (int i=1; i < 256; i++)
            palette.Entries[i] = Color.FromArgb((i*7)%256, (i*7)%256, 255);
        bitmap.Palette = palette;
        // Stuff

I don't know whether you can unpin the array after constructing the bitmap - if I were using this for production code I'd look at that more closely.