Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Forked from nuitsjp/BitmapExtensions.cs
Created August 24, 2020 14:10
Show Gist options
  • Save unitycoder/961e7f96d5dde880cee09fbe0a056066 to your computer and use it in GitHub Desktop.
Save unitycoder/961e7f96d5dde880cee09fbe0a056066 to your computer and use it in GitHub Desktop.
Convert System.Drawing.Bitmap to System.Windows.Media.ImageSource
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject([In] IntPtr hObject);
public static ImageSource ToImageSource(this Bitmap bmp)
{
var handle = bmp.GetHbitmap();
try
{
return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally { DeleteObject(handle); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment