public static System.Windows.Media.ImageSource ImageSourceFromHBitmap(Bitmap bitmap) { IntPtr handle = IntPtr.Zero; System.Windows.Media.ImageSource ret = null; try { handle = bitmap.GetHbitmap(); ret = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ret.Freeze(); } catch (Exception) { } finally { WIN32.DeleteObject(handle); } return(ret); }
public static System.Windows.Media.ImageSource ToImageSource(this Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); System.Windows.Media.ImageSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!DeleteObject(hBitmap)) { throw new Win32Exception(); } bitmapSource.Freeze(); return(bitmapSource); }