有没有一个好的方法来转换BitmapSource和位图?

据我可以告诉唯一的方法来从BitmapSource转换为位图是通过不安全的代码…像这样(来自Lesters WPF博客 ):

myBitmapSource.CopyPixels(bits, stride, 0); unsafe { fixed (byte* pBits = bits) { IntPtr ptr = new IntPtr(pBits); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap( width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppPArgb,ptr); return bitmap; } } 

做相反的事情:

 System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); 

在框架中有一个更简单的方法吗? 那它不在的原因是什么(如果不是的话)? 我会认为这是相当有用的。

我需要它的原因是因为我使用AForge在WPF应用程序中执行某些图像操作。 WPF想要显示BitmapSource / ImageSource,但是AForge在位图上工作。

有可能通过使用Bitmap.LockBits不使用不安全的代码,并将BitmapSource的像素直接复制到Bitmap

 Bitmap GetBitmap(BitmapSource source) { Bitmap bmp = new Bitmap( source.PixelWidth, source.PixelHeight, PixelFormat.Format32bppPArgb); BitmapData data = bmp.LockBits( new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb); source.CopyPixels( Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data); return bmp; } 

你可以使用这两种方法:

 public static BitmapSource ConvertBitmap(Bitmap source) { return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } public static Bitmap BitmapFromSource(BitmapSource bitmapsource) { Bitmap bitmap; using (var outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapsource)); enc.Save(outStream); bitmap = new Bitmap(outStream); } return bitmap; } 

这对我来说是完美的。

这是你想要的吗?

 Bitmap bmp = System.Drawing.Image.FromHbitmap(pBits); 

这里有一个代码来设置资源字典中的任何位图资源的透明背景(而不是Windows.Forms中经常使用的Resources.resx)。 我在InitializeComponent()方法之前调用这个方法。 方法'ConvertBitmap(Bitmap source)'和BitmapFromSource(BitmapSource bitmapsource)在上面的melvas中提到。

 private void SetBitmapResourcesTransparent() { Image img; BitmapSource bmpSource; System.Drawing.Bitmap bmp; foreach (ResourceDictionary resdict in Application.Current.Resources.MergedDictionaries) { foreach (DictionaryEntry dictEntry in resdict) { // search for bitmap resource if ((img = dictEntry.Value as Image) is Image && (bmpSource = img.Source as BitmapSource) is BitmapSource && (bmp = BitmapFromSource(bmpSource)) != null) { // make bitmap transparent and assign it back to ressource bmp.MakeTransparent(System.Drawing.Color.Magenta); bmpSource = ConvertBitmap(bmp); img.Source = bmpSource; } } } } 

这比光明简洁快捷:

  return Imaging.CreateBitmapSourceFromHBitmap( bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions() ); 

您可以在两个名称空间之间共享像素数据。 你不必转换。

使用SharedBitmapSource。 https://stackoverflow.com/a/32841840/690656