Bitmap class in WPF

泪湿孤枕 提交于 2019-12-21 19:51:14

问题


I'm working with Emgu Cv in Winforms to do face recognition using Kinect. Now, i want to move to WPF. However, the EmguCv library support only Bitmap class.

Can i use the Bitmap class (used in Winforms) in WPF ? if not, is there an other method to use Emgu cv with kinect in WPF?

Thanks.


回答1:


System.Drawing.Bitmap can not be used directly as image source for WPF, so you have to convert it to System.Windows.Media.Imaging.BitmapSource.

The best way to do it is by using Imaging.CreateBitmapSourceFromHBitmap.

You can use an extension method:

[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);

public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }

    IntPtr ip = source.GetHbitmap();
    try
    {
        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
            IntPtr.Zero, Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    }
    finally
    {
        DeleteObject(ip);
    }
}

Please note that you must invoke DeleteObject, because Bitmap.GetHbitmap() leaks a GDI handle (see this answer).

Once you have a BitmapSource, you can display it using an Image control and by setting the Source property.

You can read more about WPF imaging in this article: Imaging Overview



来源:https://stackoverflow.com/questions/12368626/bitmap-class-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!