【问题标题】:Convert System.Windows.Media.Imaging.BitmapSource to System.Drawing.Image将 System.Windows.Media.Imaging.BitmapSource 转换为 System.Drawing.Image
【发布时间】:2011-04-14 16:22:34
【问题描述】:

我将两个库捆绑在一起。一个只提供System.Windows.Media.Imaging.BitmapSource 类型的输出,另一个只接受System.Drawing.Image 类型的输入。

如何进行这种转换?

【问题讨论】:

    标签: c# .net image


    【解决方案1】:

    这是做同样事情的另一种技术。接受的答案有效,但我遇到了具有 alpha 通道的图像的问题(即使在切换到 PngBitmapEncoder 之后)。这种技术也可能更快,因为它只是在转换为兼容的像素格式后生成像素的原始副本。

    public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
    {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
            src.BeginInit();
            src.Source = bitmapsource;
            src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
            src.EndInit();
    
            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);
    
            return bitmap;
    }
    

    【讨论】:

    • 一定要处理bitmap对象! using(Bitmap bitmap = new Bitmap(...)) { ... }
    • @aholmes 为什么人们应该担心要处理的bitmap 对象?这是调用者的责任,而不是实施者的责任
    • 我忘了我为什么写那条评论了。我想我打算写using(Bitmap bitmap = BitmapFromSource(...)) {...}
    • 非常好!你能说什么时候需要转换图像格式(代码的第一部分)?
    • 在所有关于 SO 的答案中,这是迄今为止最快的
    【解决方案2】:
    private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)
    {
      System.Drawing.Bitmap bitmap;
      using (MemoryStream outStream = new MemoryStream())
      {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bitmapsource));
        enc.Save(outStream);
        bitmap = new System.Drawing.Bitmap(outStream);
      }
      return bitmap;
    }
    

    【讨论】:

    • 有一个问题:您将失去透明度(对于带有 Alpha 通道的位图)。
    猜你喜欢
    • 2015-09-28
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2015-11-02
    • 2012-02-14
    • 1970-01-01
    相关资源
    最近更新 更多