在WPF中显示Drawing.Image

时间:2012-04-09 17:59:57

标签: c# wpf image

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

如何在我的WPF应用程序中显示此内容?

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

3 个答案:

答案 0 :(得分:23)

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

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

来自this question and answers

答案 1 :(得分:16)

要将图像加载到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);

答案 2 :(得分:10)

如果使用转换器,实际上可以绑定到Image对象。您只需创建IValueConverter即可将Image转换为BitmapSource

我在转换器中使用了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中,您需要添加转换器。

<utils:ImageToBitmapSourceConverter x:Key="ImageConverter"/>

<Image Source="{Binding ThumbSmall, Converter={StaticResource ImageConverter}}"
                   Stretch="None"/>