在WPF中显示Drawing.Image

我有一个System.Drawing.Image的实例。

如何在我的WPF应用程序中显示这个?

我尝试使用img.Source但这不起作用。

我有同样的问题,并结合几个答案解决它。

 System.Drawing.Bitmap bmp; Image image; ... using (var ms = new MemoryStream()) { bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; var bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = ms; bi.EndInit(); } image.Source = bi; //bmp.Dispose(); //if bmp is not used further. Thanks @Peter 

从这个问题和答案

要将图像加载到WPF图像控件中,您需要一个System.Windows.Media.ImageSource。

您需要将Drawing.Image对象转换为ImageSource对象:

  public static BitmapSource GetImageStream(Image myImage) { var bitmap = new Bitmap(myImage); IntPtr bmpPt = bitmap.GetHbitmap(); BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPt, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //freeze bitmapSource and clear memory to avoid memory leaks bitmapSource.Freeze(); DeleteObject(bmpPt); return bitmapSource; } 

DeleteObject方法的声明。

 [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteObject(IntPtr value); 

如果使用转换器,则实际上可以绑定到Image对象。 您只需要创建一个将Image转换为BitmapSourceIValueConverter

我在转换器中使用了AlexDrenea的示例代码来完成实际工作。

 [ValueConversion(typeof(Image), typeof(BitmapSource))] public class ImageToBitmapSourceConverter : IValueConverter { [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteObject(IntPtr value); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Image myImage = (Image)value; var bitmap = new Bitmap(myImage); IntPtr bmpPt = bitmap.GetHbitmap(); BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPt, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //freeze bitmapSource and clear memory to avoid memory leaks bitmapSource.Freeze(); DeleteObject(bmpPt); return bitmapSource; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

在您的XAML中,您需要添加转换器。