如何将2D像素数组传递给BitmapSource.Create()?

时间:2011-10-17 01:42:24

标签: c#-4.0 .net-4.0

我有一个字节像素的二维数组,我想从中创建一个BitmapSource。鉴于BitmapSource.Create()需要1D数组加步幅,我应该如何传递我的2D数组呢?

我目前的解决方案是使用BlockCopy复制到中间1D数组:

int width = pixels2D.GetLength(1); int height = pixels2D.GetLength(0);
byte[] pixels1D = new byte [width * height ];
Buffer.BlockCopy(pixels2D, 0, pixels1D, 0, pixels1D.Length * sizeof(byte));
return BitmapSource.Create(width, height, 96, 96, System.Windows.Media.PixelFormats.Gray8,
                        null, pixels1D, stride: width * sizeof(byte));

但这依赖于我所理解的未定义的数组维度包装。我想要一个避免这种情况的解决方案,理想情况下避免复制数据。感谢。

1 个答案:

答案 0 :(得分:1)

据我所知,实现这个有三种方法:

1)Block Copy,效率很高;

2)For loop,将pixels2D[i,j]复制到pixels1D[i*width+j],这也是有效的;

3)Linqpixels2D.Cast<byte>().ToArray(),这很简单但很慢。