Reputation: 185
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();
Upvotes: 2
Views: 5957
Reputation: 25623
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
).
Upvotes: 6