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

前端 未结 3 969
春和景丽
春和景丽 2021-01-23 01:05

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

3条回答
  •  孤街浪徒
    2021-01-23 01:30

    If your bitmap data is uncompressed, you could probably use this System.Drawing.Bitmap constructor: 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 the Bitmap(Stream) constructor.

    EDIT:

    Since you're sending the bitmap to a web service, I suggest you encode it to begin with. 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 end, simply:

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

    Hope that helps.

提交回复
热议问题