C# 将 System.Windows.Media.ImageSource 转换为 System.Drawing.Bitmap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1201518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert System.Windows.Media.ImageSource to System.Drawing.Bitmap
提问by Jake
How can I convert a System.Windows.Media.ImageSource to a System.Drawing.Bitmap in C#?
如何在 C# 中将 System.Windows.Media.ImageSource 转换为 System.Drawing.Bitmap?
回答by Andrew Hare
Please see HOW TO USE IMAGESOURCE (NO HANDLER) IN WINFORMS AS SYSTEM.DRAWING.BITMAP (HBITMAP):
请参阅如何在 WINFORMS 中使用 IMAGESOURCE(无处理程序)作为 SYSTEM.DRAWING.BITMAP (HBITMAP):
How to easily convert WinForms System.Drawing.Bitmap into WPF ImageSource you learned from this article. Today, I'll explain how to do it contrary. Actually, all he have to do is to extract handler from BitmapSource, however, such approach is not supported, thus the only thing we can do is just copy pixels of BitmapSource (or BitmapFrame) into byte array and then copy them into the pointer of HBitmap.
如何轻松地将 WinForms System.Drawing.Bitmap 转换为您从本文中学到的 WPF ImageSource。今天,我将解释如何反其道而行之。其实他要做的就是从BitmapSource中提取handler,但是这种方式是不支持的,所以我们唯一能做的就是把BitmapSource(或BitmapFrame)的像素拷贝到字节数组中,然后拷贝到位图。
回答by kimic
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.
它是较旧的 OP,但对于其他一些人来说仍然可以派上用场,因为需要一些时间才能找到没有 dll 互操作或剪贴板黑客的更干净的解决方案。
this worked for me, you can use pngencoder to cut the image size before saving to file or rtf stream
这对我有用,您可以在保存到文件或 rtf 流之前使用 pngencoder 来缩小图像大小
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);
}