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

C# 4.0 如何将2D像素数组传递给BitmapSource.Create()?,c#-4.0,.net-4.0,C# 4.0,.net 4.0,我有一个字节像素的2D数组,我想从中创建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(pixe

我有一个字节像素的2D数组,我想从中创建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)
块拷贝
,效率高

2)
用于循环
,将
像素2d[i,j]
复制到
像素1d[i*width+j]
,这也是有效的


3)
Linq
pixels2D.Cast().ToArray()
,虽然简单但速度慢。

如果您也可以添加一些代码片段,效果会更好。