Created
November 21, 2012 16:21
-
-
Save eklimcz-zz/4125797 to your computer and use it in GitHub Desktop.
OpenCV Image to WPF Image Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static System.Drawing.Bitmap ToBitmap(this BitmapSource bitmapsource) | |
{ | |
System.Drawing.Bitmap bitmap; | |
using (var outStream = new MemoryStream()) | |
{ | |
// from System.Media.BitmapImage to System.Drawing.Bitmap | |
BitmapEncoder enc = new BmpBitmapEncoder(); | |
enc.Frames.Add(BitmapFrame.Create(bitmapsource)); | |
enc.Save(outStream); | |
bitmap = new System.Drawing.Bitmap(outStream); | |
return bitmap; | |
} | |
} | |
[DllImport("gdi32")] | |
private static extern int DeleteObject(IntPtr o); | |
/// <summary> | |
/// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source | |
/// </summary> | |
/// <param name="image">The Emgu CV Image</param> | |
/// <returns>The equivalent BitmapSource</returns> | |
public static BitmapSource ToBitmapSource(IImage image) | |
{ | |
using (System.Drawing.Bitmap source = image.Bitmap) | |
{ | |
IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap | |
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( | |
ptr, | |
IntPtr.Zero, | |
Int32Rect.Empty, | |
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); | |
DeleteObject(ptr); //release the HBitmap | |
return bs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment