2011-10-17 20 views
2

我有一個字節像素的二維數組,我想從中創建一個BitmapSource。鑑於BitmapSource.Create()需要一個一維數組加跨步,我應該如何通過我的二維數組?如何將2D像素數組傳遞給BitmapSource.Create()?

我目前的解決方案是使用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)); 

,但是這依賴於我的理解是陣列尺寸的未定義包裝。我想要一個避免這種情況的解決方案,並且理想情況下避免複製數據。謝謝。

回答

1

據我所知,有三種方法來實現這一點:

1)Block Copy,這是有效的;

2)For loop,複製pixels2D[i,j]pixels1D[i*width+j],這也是有效的;

3)Linqpixels2D.Cast<byte>().ToArray(),這很簡單但很慢。

+0

如果你可以添加一些代碼片段,它會更好。 – senaps