如何在C#中将二维数组转换为图像

如何在C#中将二维数组转换为图像

问题描述:

我在c#中有一个2D整数数组。

I have a 2D array of integers in c#.

二维数组中的每个条目都对应一个像素值

Each entry in the 2-D array correspond to a pixel value

我该如何使2-将D数组转换为图像文件(在C#中)

How can i make this 2-D array into an image file (in C#)

谢谢

这是一种非常快速但安全的方法:

Here is a very fast, albeit unsafe, way of doing it:

此示例耗时0.035毫秒

// 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));
    }
}

和结果: