Reputation: 461
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!!
Upvotes: 3
Views: 7321
Reputation: 1503429
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();
unsafe
{
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.
Upvotes: 6
Reputation: 755457
If you want the byte arrays to be processed inorder, you can do the following
byte[][] doubleArray = GetMyByteArray();
byte[] singleArray = doubleArray.SelectMany(x => x).ToArray();
MemoryStream ms = new MemoryStream(singleArray);
System.drawing.Image im = Image.FromStream(ms);
The SelectMany method essentially takes the arrays of arrays and returns the elements in order. Starting with the first element of the first array, finishing that array and then moving onto the next. This will continue until all elements are processed.
Upvotes: 3