Search code examples
c#wpfwriteablebitmap

WPF WriteableBitmap to byte array


Is there anyway to convert a WriteableBitmap to byte array? I assign the writeablebitmap to an System.Windows.Controls.Image source too if there's a way to get it from that. I tried this but got a general GDI exception on FromHBitmap.

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();

Solution

  • Your code encodes the image data in PNG format, but FromHBitmap expects raw, unencoded bitmap data.

    Try this:

    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);
    

    ...where bitmapSource is your WriteableBitmap (or any other BitmapSource).