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

时间:2011-02-25 05:24:53

标签: c#

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

2-D阵列中的每个条目对应于像素值

如何将这个2-D数组制作成图像文件(在C#中)

由于

5 个答案:

答案 0 :(得分:11)

这是一种非常快速,尽管不安全的方式:

[编辑]此示例耗时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));
    }
}

结果:

result

答案 1 :(得分:0)

如果您需要速度,请查看my Kinect sample。基本上它会创建一个内存区域并使用一个不安全的指针来向内存生成一个Int32数组。 BitmapSource对象用于将位图(图像)直接映射到同一区域。此特定示例还使用非托管内存使其与P / Invoke兼容。

This blogpost描述了使用不安全的性能差异。 部分内容包括:

请注意,您也可以使用Int32 [] - 指针而不是使用Byte [] - 指针的示例。

答案 2 :(得分:0)

如果速度不是问题 - Bitmap + SetPixel而不是保存到文件:http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.setpixel.aspx

答案 3 :(得分:0)

如果你想要一个WinForms图像,

Bitmap.LockBits应该可以工作。

答案 4 :(得分:0)

将数组投射到base64字符串中以便流式传输到Bitmap也会很慢吗?