WPF WriteableBitmap 到字节数组

sha*_*ady 2 c# wpf 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();
Run Code Online (Sandbox Code Playgroud)

Mik*_*bel 5

您的代码以 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);
Run Code Online (Sandbox Code Playgroud)

...bitmapSource你的WriteableBitmap(或任何其他人BitmapSource)在哪里。