2

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();
shady
  • 185
  • 2
  • 15

1 Answers1

6

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

Mike Strobel
  • 25,075
  • 57
  • 69
  • 1
    There is no .Format.BitsPerPixel on an WriteableBitmap object in UWP. Also, CopyPixels doesn't exist. Why there are so big differences between the same data types in WPF and UWP? – Cosmin Ioniță Jan 22 '17 at 20:21