WPF WriteableBitmap到字节数组

时间:2014-10-23 14:00:23

标签: c# wpf writeablebitmap

无论如何将WriteableBitmap转换为字节数组?我将writeablebitmap分配给System.Windows.Controls.Image源,如果有办法从中获取它。我试过这个,但在FromHBitmap上得到了一般的GDI异常。

System.Drawing.Image img = System.Drawing.Image.FromHbitmap(wb.BackBuffer);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
myarray = ms.ToArray();

1 个答案:

答案 0 :(得分:3)

您的代码以PNG格式对图像数据进行编码,但FromHBitmap需要原始未编码的位图数据。

试试这个:

var width = bitmapSource.PixelWidth;
var height = bitmapSource.PixelHeight;
var stride = width * ((bitmapSource.Format.BitsPerPixel + 7) / 8);

var bitmapData = new byte[height * stride];

bitmapSource.CopyPixels(bitmapData, stride, 0);

...其中bitmapSource是您的WriteableBitmap(或任何其他BitmapSource)。