Original: C # calls native camera
During this time, a small project needs to call the camera to take pictures, collect some information on the net and solve some minor problems, this record is used for subsequent use.
Hardware environment: Lenovo C360 integrated machine with camera
Authoring Environment: VS2010
Language: C # WPF
Download the Aforge class library and add references:
using Aforge; using Aforge.controls; using Aforge.video; using AForge.Video.DirectShow; using Size = System.Drawing.Size;
View Code
Add the Videosourceplayer control in the XAML interface, which explains slightly how to add foreign controls:
Add a new tab in the Toolbox, right-click to add a selection, browse select control DLL OK, reference control can be added to the toolbox.
Enumerate all the cameras:
New filterinfocollection (filtercategory.videoinputdevice); foreach inch videodevices) { // can make processing }
Connect the camera:
Statement: Fileterinfo info;
info = videodevices[0];//Select the first one, where flexible changes can be made
New Videocapturedevice (Videodevices[info. monikerstring); New System.Drawing.Size (214281); 1 ; = VideoSource; Videosourceplayer.start ();
Turn off the camera:
Videosourceplayer.signaltostop (); Videosourceplayer.waitforstop ();
Photo:
if(videosourceplayer.isrunning) {
String path = "E:\" BitmapSource BitmapSource=System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap (videosourceplayer.ge Tcurrentvideoframe (). Gethbitmap (), IntPtr.Zero, Int32rect.empty, Bitmapsizeoptions.fromemptyoptions ()); Pngbitmapencoder PE=NewPngbitmapencoder (); PE.FRAMES.ADD (Bitmapframe.create (BitmapSource)); stringPicname = path +"Paizhao"+". jpg"; if(File.exists (picname)) {file.delete (picname); } using(Stream stream =file.create (Picname)) {Pe.save (stream); } }
The project requires that the camera is in the monitoring state, after the picture fixed storage, not satisfied can be emptied again to take pictures, until satisfied.
The idea is to add an image control on top of Videosourceplayer because the project is made by WPF, all photos display can only add an image control, there are two points to note:
1) WPF references the WinForm control requires the use of the WindowsFormsHost control, so monitoring video and photo display is the display and hiding of control windowsformshost and image controls, so take a detour and record it.
2) The source of the image control is already bound, but the photo needs to be emptied to delete the photo resource, which means that the resource is already occupied and cannot be deleted. Solution path:
Statement: BitmapImage BMI = new System.Windows.Media.Imaging.BitmapImage ();
When used: BMI. Bgeininit ();
Bmi. UriSource = new Uri (picname);
Bmi. cacheoption = Bitmapcacheoption.onload;
Bmi. EndInit ();
Binding: This.image.Source = BMI;
C # calls the native camera