I have a 2D array of integers in c#.
Each entry in the 2-D array correspond to a pixel value
How can i make this 2-D array into an image file (in C#)
<Bitmap.LockBits should work, if you're wanting a WinForms image.
Here is a very fast, albeit unsafe, way of doing it:
[Edit] This example took 0.035 ms
// Create 2D array of integers
int width = 320;
int height = 240;
int stride = width * 4;
int[,] integers = new int[width,height];
// Fill array with random values
Random random = new Random();
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
byte[] bgra = new byte[] { (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255), 255 };
integers[x, y] = BitConverter.ToInt32(bgra, 0);
}
}
// Copy into bitmap
Bitmap bitmap;
unsafe
{
fixed (int* intPtr = &integers[0,0])
{
bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppRgb, new IntPtr(intPtr));
}
}
and the result:
Would projecting the array into a base64 string for streaming into a Bitmap
be slow too?
If you have the need for speed look at my Kinect sample. Basically it creates a memory area and uses an unsafe pointer to generate an Int32 array towards the memory. A BitmapSource object is used to map a bitmap (image) directly onto the same area. This particular example also uses unmanaged memory to make it compatible with P/Invoke.
This blogpost describes the difference in performance of using unsafe. Part from that have a look at:
Note that you can just as well make a Int32[]-pointer instead of the examples which uses Byte[]-pointer.
If speed is not a concern - Bitmap + SetPixel and than save to a file: http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.setpixel.aspx