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<
// 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;
}