DirectShowSamples-2007-July\Samples\Capture\DxSnap
Capture.cs
Capture.cs
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->/****************************************************************************
WhiletheunderlyinglibrariesarecoveredbyLGPL,thissampleisreleased
aspublicdomain.Itisdistributedinthehopethatitwillbeuseful,but
WITHOUTANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITY
orFITNESSFORAPARTICULARPURPOSE.
*****************************************************************************/
usingSystem;
usingSystem.Drawing;
usingSystem.Drawing.Imaging;
usingSystem.Collections;
usingSystem.Runtime.InteropServices;
usingSystem.Threading;
usingSystem.Diagnostics;
usingSystem.Windows.Forms;
usingDirectShowLib;
namespaceSnapShot
{
///<summary>SummarydescriptionforMainForm.</summary>
internalclassCapture:ISampleGrabberCB,IDisposable
{
#regionMembervariables
///<summary>graphbuilderinterface.</summary>
privateIFilterGraph2m_FilterGraph=null;
//UsedtosnappictureonStillpin
privateIAMVideoControlm_VidControl=null;
privateIPinm_pinStill=null;
///<summary>sowecanwaitfortheasyncjobtofinish</summary>
privateManualResetEventm_PictureReady=null;
privateboolm_WantOne=false;
///<summary>Dimensionsoftheimage,calculatedonceinconstructorforperf.</summary>
privateintm_videoWidth;
privateintm_videoHeight;
privateintm_stride;
///<summary>bufferforbitmapdata.Alwaysreleasebycaller</summary>
privateIntPtrm_ipBuffer=IntPtr.Zero;
#ifDEBUG
//Allowyouto"Connecttoremotegraph"fromGraphEdit
DsROTEntrym_rot=null;
#endif
#endregion
#regionAPIs
[DllImport("Kernel32.dll",EntryPoint="RtlMoveMemory")]
privatestaticexternvoidCopyMemory(IntPtrDestination,IntPtrSource,[MarshalAs(UnmanagedType.U4)]intLength);
#endregion
//Zerobaseddeviceindexanddeviceparamsandoutputwindow
publicCapture(intiDeviceNum,intiWidth,intiHeight,shortiBPP,ControlhControl)
{
DsDevice[]capDevices;
//Getthecollectionofvideodevices
capDevices=DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
if(iDeviceNum+1>capDevices.Length)
{
thrownewException("Novideocapturedevicesfoundatthatindex!");
}
try
{
//Setupthecapturegraph
SetupGraph(capDevices[iDeviceNum],iWidth,iHeight,iBPP,hControl);
//tellthecallbacktoignorenewimages
m_PictureReady=newManualResetEvent(false);
}
catch
{
Dispose();
throw;
}
}
///<summary>releaseeverything.</summary>
publicvoidDispose()
{
#ifDEBUG
if(m_rot!=null)
{
m_rot.Dispose();
}
#endif
CloseInterfaces();
if(m_PictureReady!=null)
{
m_PictureReady.Close();
}
}
//Destructor
~Capture()
{
Dispose();
}
///<summary>
///GettheimagefromtheStillpin.Thereturnedimagecanturnedintoabitmapwith
///Bitmapb=newBitmap(cam.Width,cam.Height,cam.Stride,PixelFormat.Format24bppRgb,m_ip);
///Iftheimageisupsidedown,youcanfixitwith
///b.RotateFlip(RotateFlipType.RotateNoneFlipY);
///</summary>
///<returns>ReturnedpointertobefreedbycallerwithMarshal.FreeCoTaskMem</returns>
publicIntPtrClick()
{
inthr;
//getreadytowaitfornewimage
m_PictureReady.Reset();
m_ipBuffer=Marshal.AllocCoTaskMem(Math.Abs(m_stride)*m_videoHeight);
try
{
m_WantOne=true;
//Ifweareusingastillpin,askforapicture
if(m_VidControl!=null)
{
//Tellthecameratosendanimage
hr=m_VidControl.SetMode(m_pinStill,VideoControlFlags.Trigger);
DsError.ThrowExceptionForHR(hr);
}
//Startwaiting
if(!m_PictureReady.WaitOne(9000,false))
{
thrownewException("Timeoutwaitingtogetpicture");
}
}
catch
{
Marshal.FreeCoTaskMem(m_ipBuffer);
m_ipBuffer=IntPtr.Zero;
throw;
}
//Gotone
returnm_ipBuffer;
}
publicintWidth
{
get
{
returnm_videoWidth;
}
}
publicintHeight
{
get
{
returnm_videoHeight;
}
}
publicintStride
{
get
{
returnm_stride;
}
}
///<summary>buildthecapturegraphforgrabber.</summary>
privatevoidSetupGraph(DsDevicedev,intiWidth,intiHeight,shortiBPP,ControlhControl)
{
inthr;
ISampleGrabbersampGrabber=null;
IBaseFiltercapFilter=null;
IPinpCaptureOut=null;
IPinpSampleIn=null;
IPinpRenderIn=null;
//Getthegraphbuilderobject
m_FilterGraph=newFilterGraph()asIFilterGraph2;
try
{
#ifDEBUG
m_rot=newDsROTEntry(m_FilterGraph);
#endif
//addthevideoinputdevice
hr=m_FilterGraph.AddSourceFilterForMoniker(dev.Mon,null,dev.Name,outcapFilter);
DsError.ThrowExceptionForHR(hr);
//Findthestillpin
m_pinStill=DsFindPin.ByCategory(capFilter,PinCategory.Still,0);
//Didn'tfindone.Isthereapreviewpin?
if(m_pinStill==null)
{
m_pinStill=DsFindPin.ByCategory(capFilter,PinCategory.Preview,0);
}
//Stillhaven'tfoundone.Needtoputasplitterinsowehave
//onestreamtocapturethebitmapfrom,andonetodisplay.Ok,we
//don't*have*todoitthatway,butwearegoingtoanyway.
if(m_pinStill==null)
{
IPinpRaw=null;
IPinpSmart=null;
//Thereisnostillpin
m_VidControl=null;
//Addasplitter
IBaseFilteriSmartTee=(IBaseFilter)newSmartTee();
try
{
hr=m_FilterGraph.AddFilter(iSmartTee,"SmartTee");
DsError.ThrowExceptionForHR(hr);
//Findthefindthecapturepinfromthevideodeviceandthe
//inputpinforthesplitter,andconnnectthem
pRaw=DsFindPin.ByCategory(capFilter,PinCategory.Capture,0);
pSmart=DsFindPin.ByDirection(iSmartTee,PinDirection.Input,0);
hr=m_FilterGraph.Connect(pRaw,pSmart);
DsError.ThrowExceptionForHR(hr);
//Nowsetthecaptureandstillpins(fromthesplitter)
m_pinStill=DsFindPin.ByName(iSmartTee,"Preview");
pCaptureOut=DsFindPin.ByName(iSmartTee,"Capture");
//Ifanyofthedefaultconfigitemsareset,performtheconfig
//ontheactualvideodevice(ratherthanthesplitter)
if(iHeight+iWidth+iBPP>0)
{
SetConfigParms(pRaw,iWidth,iHeight,iBPP);
}
}
finally
{
if(pRaw!=null)
{
Marshal.ReleaseComObject(pRaw);
}
if(pRaw!=pSmart)
{
Marshal.ReleaseComObject(pSmart);
}
if(pRaw!=iSmartTee)
{
Marshal.ReleaseComObject(iSmartTee);
}
}
}
else
{
//Getacontrolpointer(usedinClick())
m_VidControl=capFilterasIAMVideoControl;
pCaptureOut=DsFindPin.ByCategory(capFilter,PinCategory.Capture,0);
//Ifanyofthedefaultconfigitemsareset
if(iHeight+iWidth+iBPP>0)
{
SetConfigParms(m_pinStill,iWidth,iHeight,iBPP);
}
}
//GettheSampleGrabberinterface
sampGrabber=newSampleGrabber()asISampleGrabber;
//Configurethesamplegrabber
IBaseFilterbaseGrabFlt=sampGrabberasIBaseFilter;
ConfigureSampleGrabber(sampGrabber);
pSampleIn=DsFindPin.ByDirection(baseGrabFlt,PinDirection.Input,0);
//Getthedefaultvideorenderer
IBaseFilterpRenderer=newVideoRendererDefault()asIBaseFilter;
hr=m_FilterGraph.AddFilter(pRenderer,"Renderer");
DsError.ThrowExceptionForHR(hr);
pRenderIn=DsFindPin.ByDirection(pRenderer,PinDirection.Input,0);
//Addthesamplegrabbertothegraph
hr=m_FilterGraph.AddFilter(baseGrabFlt,"Ds.NETGrabber");
DsError.ThrowExceptionForHR(hr);
if(m_VidControl==null)
{
//ConnecttheStillpintothesamplegrabber
hr=m_FilterGraph.Connect(m_pinStill,pSampleIn);
DsError.ThrowExceptionForHR(hr);
//Connectthecapturepintotherenderer
hr=m_FilterGraph.Connect(pCaptureOut,pRenderIn);
DsError.ThrowExceptionForHR(hr);
}
else
{
//Connectthecapturepintotherenderer
hr=m_FilterGraph.Connect(pCaptureOut,pRenderIn);
DsError.ThrowExceptionForHR(hr);
//ConnecttheStillpintothesamplegrabber
hr=m_FilterGraph.Connect(m_pinStill,pSampleIn);
DsError.ThrowExceptionForHR(hr);
}
//Learnthevideoproperties
SaveSizeInfo(sampGrabber);
ConfigVideoWindow(hControl);
//Startthegraph
IMediaControlmediaCtrl=m_FilterGraphasIMediaControl;
hr=mediaCtrl.Run();
DsError.ThrowExceptionForHR(hr);
}
finally
{
if(sampGrabber!=null)
{
Marshal.ReleaseComObject(sampGrabber);
sampGrabber=null;
}
if(pCaptureOut!=null)
{
Marshal.ReleaseComObject(pCaptureOut);
pCaptureOut=null;
}
if(pRenderIn!=null)
{
Marshal.ReleaseComObject(pRenderIn);
pRenderIn=null;
}
if(pSampleIn!=null)
{
Marshal.ReleaseComObject(pSampleIn);
pSampleIn=null;
}
}
}
privatevoidSaveSizeInfo(ISampleGrabbersampGrabber)
{
inthr;
//GetthemediatypefromtheSampleGrabber
AMMediaTypemedia=newAMMediaType();
hr=sampGrabber.GetConnectedMediaType(media);
DsError.ThrowExceptionForHR(hr);
if((media.formatType!=FormatType.VideoInfo)||(media.formatPtr==IntPtr.Zero))
{
thrownewNotSupportedException("UnknownGrabberMediaFormat");
}
//Grabthesizeinfo
VideoInfoHeadervideoInfoHeader=(VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr,typeof(VideoInfoHeader));
m_videoWidth=videoInfoHeader.BmiHeader.Width;
m_videoHeight=videoInfoHeader.BmiHeader.Height;
m_stride=m_videoWidth*(videoInfoHeader.BmiHeader.BitCount/8);
DsUtils.FreeAMMediaType(media);
media=null;
}
//SetthevideowindowwithinthecontrolspecifiedbyhControl
privatevoidConfigVideoWindow(ControlhControl)
{
inthr;
IVideoWindowivw=m_FilterGraphasIVideoWindow;
//Settheparent
hr=ivw.put_Owner(hControl.Handle);
DsError.ThrowExceptionForHR(hr);
//Turnoffcaptions,etc
hr=ivw.put_WindowStyle(WindowStyle.Child|WindowStyle.ClipChildren|WindowStyle.ClipSiblings);
DsError.ThrowExceptionForHR(hr);
//Yes,makeitvisible
hr=ivw.put_Visible(OABool.True);
DsError.ThrowExceptionForHR(hr);
//Movetoupperleftcorner
Rectanglerc=hControl.ClientRectangle;
hr=ivw.SetWindowPosition(0,0,rc.Right,rc.Bottom);
DsError.ThrowExceptionForHR(hr);
}
privatevoidConfigureSampleGrabber(ISampleGrabbersampGrabber)
{
inthr;
AMMediaTypemedia=newAMMediaType();
//SetthemediatypetoVideo/RBG24
media.majorType=MediaType.Video;
media.subType=MediaSubType.RGB24;
media.formatType=FormatType.VideoInfo;
hr=sampGrabber.SetMediaType(media);
DsError.ThrowExceptionForHR(hr);
DsUtils.FreeAMMediaType(media);
media=null;
//Configurethesamplegrabber
hr=sampGrabber.SetCallback(this,1);
DsError.ThrowExceptionForHR(hr);
}
//SettheFramerate,andvideosize
privatevoidSetConfigParms(IPinpStill,intiWidth,intiHeight,shortiBPP)
{
inthr;
AMMediaTypemedia;
VideoInfoHeaderv;
IAMStreamConfigvideoStreamConfig=pStillasIAMStreamConfig;
//Gettheexistingformatblock
hr=videoStreamConfig.GetFormat(outmedia);
DsError.ThrowExceptionForHR(hr);
try
{
//copyoutthevideoinfoheader
v=newVideoInfoHeader();
Marshal.PtrToStructure(media.formatPtr,v);
//ifoverridingthewidth,setthewidth
if(iWidth>0)
{
v.BmiHeader.Width=iWidth;
}
//ifoverridingtheHeight,settheHeight
if(iHeight>0)
{
v.BmiHeader.Height=iHeight;
}
//ifoverridingthebitsperpixel
if(iBPP>0)
{
v.BmiHeader.BitCount=iBPP;
}
//Copythemediastructureback
Marshal.StructureToPtr(v,media.formatPtr,false);
//Setthenewformat
hr=videoStreamConfig.SetFormat(media);
DsError.ThrowExceptionForHR(hr);
}
finally
{
DsUtils.FreeAMMediaType(media);
media=null;
}
}
///<summary>Shutdowncapture</summary>
privatevoidCloseInterfaces()
{
inthr;
try
{
if(m_FilterGraph!=null)
{
IMediaControlmediaCtrl=m_FilterGraphasIMediaControl;
//Stopthegraph
hr=mediaCtrl.Stop();
}
}
catch(Exceptionex)
{
Debug.WriteLine(ex);
}
if(m_FilterGraph!=null)
{
Marshal.ReleaseComObject(m_FilterGraph);
m_FilterGraph=null;
}
if(m_VidControl!=null)
{
Marshal.ReleaseComObject(m_VidControl);
m_VidControl=null;
}
if(m_pinStill!=null)
{
Marshal.ReleaseComObject(m_pinStill);
m_pinStill=null;
}
}
///<summary>samplecallback,NOTUSED.</summary>
intISampleGrabberCB.SampleCB(doubleSampleTime,IMediaSamplepSample)
{
Marshal.ReleaseComObject(pSample);
return0;
}
///<summary>buffercallback,COULDBEFROMFOREIGNTHREAD.</summary>
intISampleGrabberCB.BufferCB(doubleSampleTime,IntPtrpBuffer,intBufferLen)
{
//NotethatwedependononlybeingcalledoncepercalltoClick.Otherwise
//asecondcallcanoverwritethepreviousimage.
Debug.Assert(BufferLen==Math.Abs(m_stride)*m_videoHeight,"Incorrectbufferlength");
if(m_WantOne)
{
m_WantOne=false;
Debug.Assert(m_ipBuffer!=IntPtr.Zero,"Unitializedbuffer");
//Savethebuffer
CopyMemory(m_ipBuffer,pBuffer,BufferLen);
//Pictureisready.
m_PictureReady.Set();
}
return0;
}
}
}
Form1.cs
相关推荐
C# WinForm DirectShow视频采集及图片抓取实例DxSnap 抓拍 视频
基于微软的DirectShow.dll的二次开发 1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个) ...这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正
c# winform实例大全(198个Csharp WinForm实例源码)
经典C#WinForm小实例,真实代码。日常实用性较强,有需要欢迎关顾小店。
C# winform 实现弹出的等待对话框实例 C# winform 实现弹出的等待对话框实例
C# Winform实现图像的动态采集,采集到的流媒体按照*.wam或者任意一种Windows Media Player 11可以播放的文件格式, 并获取流媒体采集结束时的最后画面作为流媒体的封面。 要求有录像功能:“开始录像”、“暂停...
c# winform ListView实现图片浏览
C#WinForm 三级分类 实例 源代码 C#WinForm 三级分类 实例 源代码 C#WinForm 三级分类 实例 源代码 本人QQ:280067279,加时注明:CSDN,我也想多认识些编程的朋友.
c# winform 绘制多行文本:自动换行:文本c# winform 绘制多行文本:自动换行:文本c# winform 绘制多行文本:自动换行:文本c# winform 绘制多行文本:自动换行:文本c# winform 绘制多行文本:自动换行:文本c# winform 绘制...
C#winform窗体2种上传图片方法,附有源码,可自行修改,亦可修改上传格式达到上传文件效果
C#WinForm基于BS构架实现CS实例及源代码.zipC#WinForm基于BS构架实现CS实例及源代码.zipC#WinForm基于BS构架实现CS实例及源代码.zipC#WinForm基于BS构架实现CS实例及源代码.zip 本人QQ:280067279,加时注明:CSDN,我...
"198个经典C#WinForm实例源码"包括: 1-窗体技巧 2-控件操作 3-图像操作 4-报表打印 5-系统操作 6-文件处理 7-网络操作 8-数据库操作 9-加密解密 10-硬件读写 11-游戏设计 "超赞的198个经典C#WinForm实例源码.zip " ...
自己用C#写的DirectShow接口实现的媒体播放器,实现了播放、暂停、停止、快进、快退、播放列表、打开文件、将文件夹内所有媒体文件加入播放列表、音量控制、拖动进度条等功能。支持*.mpg;*.avi;*.flv;*.wma;*.mov;*....
C#+WinForm视频播放器.是一款以.net开发的一款播放器
c# winform pdf转换各种格式图片html,text等,功能强大。不用注册,请自己下载 GhostScript 8.64安装后目录下的gsdll32.dll放置在bin文件夹下。
198个经典C#WinForm实例源码 1、窗体 2、控件 3、图像 4、报表 5、系统 6、文件 7、网络 8、数据库 9、加密、解密 10、硬件读写
198个 C# Winform实例源码,适用于学习winform开发技巧的同学
经典的c#源代码,涉及面广,适合小白学习
不错的C#WinForm实例源码适合研究学习技术不错的C#WinForm实例源码适合研究学习技术 1.适合学生做毕业设计参考模板。 2.适合程序员学习开发研究用 3.适合小公司做项目参不错的C#WinForm实例源码适合研究学习技术源码...
C# WinForm源代码,可以实现定时截取当前屏幕,然后存为本地图片,再将其上传至远程服务器端,上传图片到服务器。也包含上传文件到服务器端的方法。通过Ftp协议上传,更改源代码中ftp中IP地址、用户名及密码即可使用...