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<
I know this has been answered, but here are a couple of extension methods (for .NET 3.0+) that do the conversion. :)
///
/// Converts a into a WPF .
///
/// The source image.
/// A BitmapSource
public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
{
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);
var bitSrc = bitmap.ToBitmapSource();
bitmap.Dispose();
bitmap = null;
return bitSrc;
}
///
/// 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 BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
BitmapSource bitSrc = null;
var hBitmap = source.GetHbitmap();
try
{
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
finally
{
NativeMethods.DeleteObject(hBitmap);
}
return bitSrc;
}
and the NativeMethods class (to appease FxCop)
///
/// FxCop requires all Marshalled functions to be in a class called NativeMethods.
///
internal static class NativeMethods
{
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
}