wpf WPF中的位图类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12368626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bitmap class in WPF
提问by Rafik Haceb
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 Bitmapclass.
我正在使用 Winforms 中的 Emgu Cv 使用 Kinect 进行人脸识别。现在,我想转移到 WPF。但是,EmguCv 库仅支持Bitmap类。
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?
我可以在 WPF 中使用 Bitmap 类(在 Winforms 中使用)吗?如果没有,是否还有其他方法可以在 WPF 中使用 Emgu cv 和 kinect?
Thanks.
谢谢。
回答by Paolo Moretti
System.Drawing.Bitmapcan not be used directly as image source for WPF, so you have to convert it to System.Windows.Media.Imaging.BitmapSource.
System.Drawing.Bitmap不能直接用作 WPF 的图像源,因此您必须将其转换为System.Windows.Media.Imaging.BitmapSource.
The best way to do it is by using Imaging.CreateBitmapSourceFromHBitmap.
最好的方法是使用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 thisanswer).
请注意,您必须调用DeleteObject,因为会Bitmap.GetHbitmap()泄漏 GDI 句柄(请参阅此答案)。
Once you have a BitmapSource, you can display it using an Imagecontrol and by setting the Sourceproperty.
一旦有了BitmapSource,您就可以使用Image控件并通过设置Source属性来显示它。
You can read more about WPF imaging in this article: Imaging Overview
您可以在本文中阅读有关 WPF 成像的更多信息:成像概述

