If by chance you’re progressively migrating a legacy WinForms application to WPF, at some point you’ll have to use existing bitmaps and convert them to the WPF equivalent one.
It seems this is a FAQ in the forums, and some of the solutions that I saw that use the System.Windows.Interop namespace, have memory leak issues. When creating a GDI bitmap object, we must release its memory as soon as possible and people are missing this important step.
That said, I’ve decided to share the following code snippet that you can use to convert a Bitmap to an ImageSource.
public static class BitmapExtensions
{
public static ImageSource ToImageSource(this Bitmap bitmap)
{
var hbitmap = bitmap.GetHbitmap();
try
{
var imageSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bitmap.Width, bitmap.Height));
return imageSource;
}
finally
{
NativeMethods.DeleteObject(hbitmap);
}
}
}
public static class NativeMethods
{
[DllImport("gdi32")]
public static extern int DeleteObject(IntPtr hObject);
}