5

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#)

Thanks

Ahsan Kahoot
  • 53
  • 1
  • 1
  • 3

5 Answers5

12

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:

result

tbridge
  • 1,754
  • 1
  • 18
  • 35
0

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.

Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97
0

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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

Bitmap.LockBits should work, if you're wanting a WinForms image.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • @ozcanovunc: The grammar was perfect already. You may want to read about the present progressive tense. – Ben Voigt May 19 '16 at 15:10
0

Would projecting the array into a base64 string for streaming into a Bitmap be slow too?

Matt Kocaj
  • 11,278
  • 6
  • 51
  • 79