Load a WPF BitmapImage from a System.Drawing.Bitmap

前端 未结 10 2165
天涯浪人
天涯浪人 2020-11-22 04:39

I have an instance of a System.Drawing.Bitmap and would like to make it available to my WPF app in the form of a System.Windows.Media.Imaging.BitmapImage<

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 05:28

    // at class level;
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);    // https://stackoverflow.com/a/1546121/194717
    
    
    ///  
    /// Converts a  into a WPF . 
    ///  
    /// Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. 
    ///  
    /// The source bitmap. 
    /// A BitmapSource 
    public static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
    {
        var hBitmap = source.GetHbitmap();
        var result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    
        DeleteObject(hBitmap);
    
        return result;
    }
    

提交回复
热议问题