Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. /// <summary>
  2. /// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
  3. /// </summary>
  4. /// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
  5. /// </remarks>
  6. /// <param name="source">The source bitmap.</param>
  7. /// <returns>A BitmapSource</returns>
  8. public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
  9. {
  10. BitmapSource bitSrc = null;
  11.  
  12. var hBitmap = source.GetHbitmap();
  13.  
  14. try
  15. {
  16. bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
  17. hBitmap,
  18. IntPtr.Zero,
  19. Int32Rect.Empty,
  20. BitmapSizeOptions.FromEmptyOptions());
  21. }
  22. catch (Win32Exception)
  23. {
  24. bitSrc = null;
  25. }
  26. finally
  27. {
  28. NativeMethods.DeleteObject(hBitmap);
  29. }
  30.  
  31. return bitSrc;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement