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

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

2-Darrays中的每个条目对应于像素值

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

谢谢

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

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

结果:

结果

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

这篇博文描述了使用不安全的性能差异。 部分来看看:

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

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

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

如果你想要一个WinForms图像, Bitmap.LockBits应该可以工作。