Convert System.Windows.Media.ImageSource to System.Drawing.Bitmap

前端 未结 2 617
庸人自扰
庸人自扰 2020-11-30 14:04

How can I convert a System.Windows.Media.ImageSource to a System.Drawing.Bitmap in C#?

2条回答
  •  忘掉有多难
    2020-11-30 14:33

    its older OP, but still it can come handy for some other people, as it took some time to find cleaner solution without dll interop or clipboard hacks.

    this worked for me, you can use pngencoder to cut the image size before saving to file or rtf stream

    private System.Drawing.Image ImageWpfToGDI(System.Windows.Media.ImageSource image) {
      MemoryStream ms = new MemoryStream();
      var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
      encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image as System.Windows.Media.Imaging.BitmapSource));
      encoder.Save(ms);
      ms.Flush();      
      return System.Drawing.Image.FromStream(ms);
    }
    

提交回复
热议问题