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();
3
  • where is the WriteableBitmap in your code? Commented Oct 23, 2014 at 14:07
  • Declared in the class scope, but I edited it to make more sense. Commented Oct 23, 2014 at 14:31
  • now that you changed Data to BackBuffer it makes more sense Commented Oct 23, 2014 at 14:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.