如何在C#中将System.Windows.Media.ImageSource转换为System.Drawing.Bitmap?
虽然这是一个旧的问题,但它仍然对其他人有用,因为花费了一些时间才能找到没有dll交互或剪贴板黑客的更干净的解决方案。
对我来说,这个方法有效,你可以使用png编码器在保存到文件或rtf流之前缩小图像尺寸。
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);
}
从本文中学习了如何轻松将WinForms System.Drawing.Bitmap转换为WPF ImageSource。今天,我将解释如何相反地做到这一点。实际上,我们所要做的就是从BitmapSource中提取处理程序,但是这种方法不受支持,因此我们唯一能做的就是将BitmapSource(或BitmapFrame)的像素复制到字节数组中,然后将它们复制到HBitmap的指针中。
var ms = new MemoryStream(); var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)image)); encoder.Save(ms); ms.Flush(); var btm = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms); return btm;
} - Dariusz Wasacz