WPF/WinForms/GDI interop: converting a WriteableBitmap to a System.Drawing.Image?

Judah Gabriel Himango picture Judah Gabriel Himango · Jul 13, 2010 · Viewed 7.5k times · Source

How can I convert a WPF WriteableBitmap object to a System.Drawing.Image?

My WPF client app sends bitmap data to a web service, and the web service needs to construct a System.Drawing.Image on that end.

I know I can get the data of a WriteableBitmap, send the info over to the web service:

// WPF side:

WriteableBitmap bitmap = ...;
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int[] pixels = bitmap.Pixels;

myWebService.CreateBitmap(width, height, pixels);

But on the web service end, I don't know how to create a System.Drawing.Image from this data.

// Web service side:

public void CreateBitmap(int[] wpfBitmapPixels, int width, int height)
{
   System.Drawing.Bitmap bitmap = ? // How can I create this?
}

Answer

andyp picture andyp · Jul 13, 2010

this blog post shows how to encode your WriteableBitmap as a jpeg image. Perhaps that helps?

If you really want to transfer the raw image data (pixels) you could:

  1. create a System.Drawing.Bitmap with the correct size
  2. iterate over your raw data, convert the raw data to a System.Drawing.Color (e.g. via Color.FromArgb() and set each pixel color in the newly created image via SetPixel()

I'd definitely prefer the first solution (the one described in the blog post).