How to capture image from webcam in C#

By FoxLearn 11/25/2024 9:41:44 AM   382
To capture an image from a webcam in a C# Windows Forms application, you can use the AForge.NET

This guide will walk you through the basics of webcam integration in C# and provide a simple example that captures an image using your webcam.

How to capture image from webcam in c# windows application?

First, Create a new Windows Forms Application, then add a PictureBox to display the webcam feed and add a Button to trigger the image capture.

capture image from webcam in c#

Next, you need to install the AForge.Video and AForge.Video.DirectShow NuGet packages.

You can install them using the NuGet Package Manager:

aforge.net

C# Webcam Capture Image Example

We'll need to import the AForge.NET libraries, set up the video capture device, and capture a still image.

using AForge.Video;
using AForge.Video.DirectShow;

//setup
FilterInfoCollection videoDevices; // To store the available video devices
VideoCaptureDevice videoSource;    // To capture video from the webcam
Bitmap currentFrame;               // Current frame from webcam

When the form is loaded, the program searches for available video devices. It selects the first available device and starts capturing frames from it.

private void Form1_Load(object sender, EventArgs e)
{
    // Get available video devices
    videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    if (videoDevices.Count == 0)
    {
        MessageBox.Show("No video devices found.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }
    // Use the first available video device
    videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
    // Attach the NewFrame event to capture frames
    videoSource.NewFrame += VideoSource_NewFrame;

    // Start capturing the video
    videoSource.Start();
}

The FilterInfoCollection class is used to fetch all available video input devices on your machine.

The VideoCaptureDevice object is responsible for capturing video frames from the selected device.

The NewFrame event handler is triggered every time the webcam captures a new frame. We store the captured frame in a Bitmap object and update the display in a PictureBox.

// c# webcam video capture
private void VideoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
    // Dispose of the previous frame
    if (currentFrame != null)
        currentFrame.Dispose();

    // Capture the current frame
    currentFrame = (Bitmap)eventArgs.Frame.Clone();

    // Display the frame in the PictureBox
    pictureBox.Image = currentFrame;
}

When the user clicks the capture button, the current frame is saved to disk as a .jpg image.

// c# webcam capture image example
private void btnCapture_Click(object sender, EventArgs e)
{
    if (currentFrame != null)
    {
        using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "JPG|*.jpg" })
        {
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                // Save the captured image
                currentFrame.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                MessageBox.Show("Image captured and saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

When the form is closed, the video capture device is stopped and the resources are released.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (videoSource.IsRunning)
    {
        videoSource.SignalToStop();
        videoSource.WaitForStop();
    }
    if (currentFrame != null)
        currentFrame.Dispose();
}

Finally, run the application, then press the Capture button to capture an image from the webcam and save it to disk.

If you have multiple webcams, you may need to adjust which one to select by modifying videoDevices[0] to a different index.

This simple "C# webcam capture image example" demonstrates how to access a webcam, capture an image, and save it using AForge.NET