【问题标题】:Convert System.Windows.Media.ImageSource to System.Drawing.Bitmap将 System.Windows.Media.ImageSource 转换为 System.Drawing.Bitmap
【发布时间】:2010-11-15 03:35:50
【问题描述】:

如何在 C# 中将 System.Windows.Media.ImageSource 转换为 System.Drawing.Bitmap?

【问题讨论】:

    标签: c# wpf image


    【解决方案1】:

    它较旧的 OP,但对于其他人来说仍然可以派上用场,因为它需要一些时间才能找到没有 dll 互操作或剪贴板黑客的更清洁的解决方案。

    这对我有用,您可以在保存到文件或 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);
    }
    

    【讨论】:

    • 如果您需要转换带有 alpha 通道的图像(带有透明部分),请使用 System.Windows.Media.Imaging.PngBitmapEncoder() 而不是 System.Windows.Media.Imaging.BmpBitmapEncoder()。
    • @DariuszWasacz 我无法得到这个答案。它抱怨 image.Source 不起作用:'System.Drawing.Image' 不包含'Source' 的定义,并且没有扩展方法'Source' 接受'System.Drawing.Image' 类型的第一个参数可以可以找到。 我检查了 MSDN 并且 Image 没有 Source 属性。您知道需要修复什么吗?
    • @kayleeFrye_onDeck:请注意 System.Drawing 和 System.Windows.Media 命名空间都包含类“图像”。看起来您在参数“System.Windows.Media.Image image”和“System.Drawing.Image”中省略了命名空间是从 using 语句中获取的。请检查您的代码是否与上述完全相同。
    • 我觉得我在这里遗漏了一些东西,@DariuszWasacz。你是对的,因为它使用的是 System.Drawing.Image,所以对此表示赞赏,但我找不到 System.Windows.Media 的“Image”成员。我能找到的最接近的是 System.Windows.Media.ImageSource。由于您上面的代码使用了 Image 的 .Source 属性,这似乎是逻辑上的飞跃。
    • @kayleeFrye_onDeck:上面的代码最初不是我的 :-)。我的代码是这样的: public static System.Drawing.Image ImageWpfToGdi2(this ImageSource image) { var ms = new MemoryStream(); var 编码器 = 新 System.Windows.Media.Imaging.PngBitmapEncoder();编码器.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)image));编码器。保存(毫秒); ms.Flush(); var btm = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);返回 btm; }
    【解决方案2】:

    请看HOW TO USE IMAGESOURCE (NO HANDLER) IN WINFORMS AS SYSTEM.DRAWING.BITMAP (HBITMAP):

    如何轻松转换 WinForms System.Drawing.Bitmap 到 WPF 你从中学到的 ImageSource 文章。今天,我将解释如何做 它相反。其实他只需要 做的是从中提取处理程序 但是,BitmapSource 这种方法 不支持,因此唯一的 我们可以做的只是复制像素 BitmapSource(或BitmapFrame)成 字节数组,然后将它们复制到 HBitmap的指针。

    【讨论】:

    • 这篇文章和之前的文章都是相同的方法:将位图扫描线复制到字节数组,然后从内存块创建位图。位图假定内存块在位图生存期内包含扫描线。但是,在离开固定(字节* pB = 位)代码后,内存可能会被 .net 内存管理器覆盖,并且位图会损坏。解决方法是使用 Marshal.AllocHGlobal,但是这种情况下内存块必须由用户代码维护(即:必须由 Marshal.FreeHGlobal 使用后释放)。
    • 链接已失效;这就是为什么我们要求人们发布答案而不是链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2017-06-19
    • 2011-08-07
    • 2022-01-16
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多