Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert 2-D array into Image in c#

Tags:

c#

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

like image 502
Ahsan Kahoot Avatar asked Feb 25 '11 05:02

Ahsan Kahoot


1 Answers

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

like image 177
tbridge Avatar answered Oct 18 '22 02:10

tbridge