SoFunction
Updated on 2025-03-06

C# implementation to call the camera instance

The examples in this article are derived from a project where you need to call the camera of the machine to take photos and share them with you for your reference. The specific steps are as follows:

Hardware environment: Lenovo C360 all-in-one machine, comes with a camera

Writing environment: vs2010

Language: C# WPF

Implementation steps:

Download the AForge class library and add a reference:

using AForge;
using ;
using ;
using ;
using Size = ;

Add VideoSourcePlayer control in the xaml interface. This time, I explain how to add external controls:

Add a new tab in the toolbox, right-click to add the selection item, browse the selection control dll to confirm, and refer to the control to add it to the toolbox.

Enumerate all cameras:

FilterInfoCollection videoDevices;
videoDevices = new FilterInfoCollection();

foreach (FilterInfo device in videoDevices)
{
  // Can be processed}

Connect the camera:

statement:

FileterInfo info;
info = videoDevices[0];//Select the first one, you can make flexible changes here
VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[);
 = new (214, 281);
 = 1;

 = videoSource;
();

Turn off the camera:

();
();

Photograph:

if ()
{
string path = "e:\"
  BitmapSource bitmapSource = (
  ().GetHbitmap(),
  ,
  ,
  ());
  PngBitmapEncoder pE = new PngBitmapEncoder();
  ((bitmapSource));
  string picName = path + "paizhao" + ".jpg";
  if ((picName))
  {
 (picName);
  }
  using (Stream stream = (picName))
  {
 (stream);
  }
}

The project requires that the camera is in the monitoring state, and the screen is fixed after taking the photo. If you are not satisfied, you can clear it and take the photo again until you are satisfied.

The method is to add an image control on the videoSourcePlayer. Because the project is made by WPF, all photos can only add image controls. There are two points to note:

1) WPF requires the use of WindowsFormsHost control to refer to the winform control, so when monitoring videos and photos are displayed, the display and hidden of the WindowsFormsHost and image controls. I took a detour here so I recorded it.

2) The source of the image control has been bound, but the photo needs to be cleared and deleted. The system prompt roughly means that the resource has been occupied and cannot be deleted. Solution:

statement:

BitmapImage bmi = new ();

When using:

();

 = new Uri(picName);

 = ;

();

Bind:

 = bmi;

I hope this article will be helpful to everyone's C# programming.