将System.Windows.Media.Imaging.BitmapSource转换为System.Drawing.Image

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

如何进行转换?

 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通道的图像问题(甚至在切换到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; }