System.Drawing.Bitmap
can not be used directly as image source for WPF, so you have to convert it to System.Windows.Media.Imaging.BitmapSource
.
The best way to do it is by using Imaging.CreateBitmapSourceFromHBitmap
.
You can use an extension method:
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
IntPtr ip = source.GetHbitmap();
try
{
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
}
Please note that you must invoke DeleteObject
, because Bitmap.GetHbitmap()
leaks a GDI handle (see this answer).
Once you have a BitmapSource
, you can display it using an Image
control and by setting the Source
property.
You can read more about WPF imaging in this article: Imaging Overview