在WPF中显示Drawing.Image

use*_*692 23 c# wpf image

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

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

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

Bad*_*boy 24

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

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
Run Code Online (Sandbox Code Playgroud)

这个问题和答案


Ale*_*nea 20

要将图像加载到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;
    }
Run Code Online (Sandbox Code Playgroud)

DeleteObject方法的声明.

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


bur*_*t11 12

如果使用转换器,则实际上可以绑定到该Image对象.您只需要创建一个IValueConverter将其转换Image为a的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

<Image Source="{Binding ThumbSmall, Converter={StaticResource ImageConverter}}"
                   Stretch="None"/>
Run Code Online (Sandbox Code Playgroud)