最近想通过DirectShow获取摄像头所支持分辨率,但发现基本都是C++的代码,虽然俺对C++也很喜欢,但现在是要在C#上实现呀~好吧,只能自己从C++转为C#了,其中有些难点就是结构体与接口的命名规则有了一些小小的改变。
using
System;
using
System.Collections.Generic;
using
System.Drawing;
using
System.Runtime.InteropServices;
using
DirectShowLib;
///
/// 获取摄像头所支持的分辨率
///
/// 华仔103
public void GetCaptureSupportSize(ICaptureGraphBuilder2 capGraph,
IBaseFilter captureFilter)
{
object streamConfig;
// 获取配置接口
int hr = capGraph.FindInterface(PinCategory.Capture,
MediaType.Video,
captureFilter,
typeof(IAMStreamConfig).GUID,
out streamConfig);
DsError.ThrowExceptionForHR(hr);
var videoStreamConfig = streamConfig as IAMStreamConfig;
if (videoStreamConfig == null)
{
throw new Exception("Failed to get IAMStreamConfig");
}
int iCount;//好吧,我承认这是C++的变量命名方法,可我就是不想改~
int iSize;
VideoStreamConfigCaps vscc = new VideoStreamConfigCaps();
hr = videoStreamConfig.GetNumberOfCapabilities(out iCount, out
iSize);
DsError.ThrowExceptionForHR(hr);
// 判断为正确获取的信息
if (Marshal.SizeOf(vscc) == iSize)
{
for (int i = 0; i < iCount; ++i)
{
// 分配非托管内存
IntPtr pVscc = Marshal.AllocCoTaskMem(Marshal.SizeOf(vscc));
AMMediaType amMediaType;
hr = videoStreamConfig.GetStreamCaps(i, out amMediaType,
pVscc);
DsError.ThrowExceptionForHR(hr);
// 如果为视频信息
if (amMediaType.majorType == MediaType.Video &&
amMediaType.formatType == FormatType.VideoInfo)
{
Marshal.StructureToPtr(vscc, pVscc, false);
var videoInfoHeader = new VideoInfoHeader();
Marshal.PtrToStructure(amMediaType.formatPtr, videoInfoHeader);
// 获取摄像头所支持的分辨率
int width = videoInfoHeader.BmiHeader.Width;
int height = videoInfoHeader.BmiHeader.Height;
}
// 释放非托管内存
Marshal.FreeCoTaskMem(pVscc);
DsUtils.FreeAMMediaType(amMediaType);
}
}
return;
}
加载中,请稍候......