如何将 2D 像素数组传递给 BitmapSource.Create()?
我有一个字节像素的二维数组,我想从中创建 BitmapSource。鉴于 BitmapSource.Create() 需要一个 1D 数组加上步幅,我应该如何传递我的 2D 数组?
我当前的解决方案是使用 BlockCopy 复制到中间一维数组:
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));
但这依赖于我所理解的未定义的数组维度打包。我想要一个可以避免这种情况的解决方案,并且最好避免复制数据。谢谢。
I have a 2D array of byte pixels from which I want to create a BitmapSource. Given BitmapSource.Create() requires a 1D array plus stride, how should I pass my 2D array?
My current solution is to use BlockCopy to copy to an intermediate 1D array:
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));
but this relies on what I understand to be undefined packing of array dimensions. I would like a solution that avoids this, and ideally avoids copying the data. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,有3种方法可以实现:
1)
Block Copy
,效率较高;2)
For循环
,复制pixels2D[i,j]
到pixels1D[i*width+j]
,这也是高效的;3)
Linq
、pixels2D.Cast().ToArray()
,简单但速度慢。To my knowledge there are three methods to implement this:
1)
Block Copy
, which is efficient;2)
For loop
, to copypixels2D[i,j]
topixels1D[i*width+j]
, which is also efficient;3)
Linq
,pixels2D.Cast<byte>().ToArray()
, which is simple but slow.