最近想用C#写一个camera的应用。搜索了Google和StackOverflow,发现大部分的sample用了WIA或者DirectShow。WIA和DirectShow都没有直接提供C#接口,所以实现起来也比较复杂。试着运行了几个WIA的工程,在Windows10上还不起作用。发现微软提供了一个MediaCapture类,包含了丰富的C#接口,可用于音频,视频。要用这个类,就需要创建一个UWP工程。这里分享下如何使用MediaCapture的C#接口来获取camera的每一帧数据。
微软示例
微软在GitHub上放了大量的UWP示例,里面包含了各种camera的接口使用方法。
在Android中要获取camera的每一帧数据,可以通过onPreviewCallback的回调函数实现。参考CameraFrames这个示例,也可以实现类似的功能。
如何创建Windows Webcam应用
1. 在package.appxmanifest中获取webcam权限:
2. 创建image element用于绘制webcam的预览界面:
3. 通过Image Element初始化FrameRenderer :
_frameRenderer = new FrameRenderer(PreviewImage);
4. 初始化MediaCapture对象:
// Create a new media capture object.
_mediaCapture = new MediaCapture();
var settings = new MediaCaptureInitializationSettings()
{
// Select the source we will be reading from.
SourceGroup = groupModel.SourceGroup,
// This media capture has exclusive control of the source.