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

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

My WPF client application sends raster data to the web service, and the web service needs to create System.Drawing.Image for this purpose.

I know that I can get WriteableBitmap data, send information to a web service:

// WPF side: WriteableBitmap bitmap = ...; int width = bitmap.PixelWidth; int height = bitmap.PixelHeight; int[] pixels = bitmap.Pixels; myWebService.CreateBitmap(width, height, pixels); 

But at the end of the web service, I do not know how to create 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? } 
+2
source share
3 answers

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

If you really want to transfer raw image data (pixels), you can:

I would prefer the first solution (described in the blog).

+3
source

If your raster data is uncompressed, you can probably use this constructor System.Drawing.Bitmap : Bitmap (Int32, Int32, Int32, PixelFormat, IntPtr) .

If the bitmap is encoded as jpg or png, create a MemoryStream from the bitmap data and use it with Bitmap (Stream) .

EDIT:

Since you are sending a bitmap to a web service, I suggest you encode it for starters. There are several encoders in the System.Windows.Media.Imaging namespace . For example:

  WriteableBitmap bitmap = ...; var stream = new MemoryStream(); var encoder = new JpegBitmapEncoder(); encoder.Frames.Add( BitmapFrame.Create( bitmap ) ); encoder.Save( stream ); byte[] buffer = stream.GetBuffer(); // Send the buffer to the web service 

On the receiving side, simply:

  var bitmap = new System.Drawing.Bitmap( new MemoryStream( buffer ) ); 

Hope this helps.

+3
source

The question is for WPF, and Pixels not a WriteableBitmap property. Some of the answers here point to SilverLight articles, so I suspect this might be the difference between WPF and SilverLight.

0
source

All Articles