How to easily record from a webcam in C#

What is the easiest way to use a webcam in C# and record from it? If you search for an answer to this question you’ll find a lot of articles in the internet but most of them are many pages long and very confusing. However that isn’t really necessary. With the aid of the AForge.NET library you can do the given task really easy. Just a few lines of C# code are enough to drive your webcam and capture images from it. In the following I’ll show you how to handle the AForge library.

What do you need?

  • The AForge.Video.dll together with the AForge.Video.DirectShow.dll
    Both dlls can be found on the AForge website inside the “(libs only)” zip-archive.
  • A simple winforms-application, with a picturebox on its gui

At first you have to reference the both dlls and write the using-statements for them. After that you have to create two eventhandlers. One for the FormLoad-event and another one for the FormClosed-event. (If you work with Microsofts Visual Studio you can do that out of its visual designer.) The rest can be explained using the following source code and its comments.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Create using directives for easier access of AForge library's methods
using AForge.Video;
using AForge.Video.DirectShow;

namespace aforgeWebcamTutorial
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Create webcam object
        VideoCaptureDevice videoSource;

        private void Form1_Load(object sender, EventArgs e)
        {
            //List all available video sources. (That can be webcams as well as tv cards, etc)
            FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            //Check if atleast one video source is available
            if (videosources != null)
            {
                        //For example use first video device. You may check if this is your webcam.
                        videoSource = new VideoCaptureDevice(videosources[0].MonikerString);

                        try
                        {
                            //Check if the video device provides a list of supported resolutions
                            if (videoSource.VideoCapabilities.Length > 0)
                            {
                                string highestSolution = "0;0";
                                //Search for the highest resolution
                                for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)                                 {                                     if (videoSource.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
                                        highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
                                }
                                //Set the highest resolution as active
                                videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(';')[1])];
                            }
                        }
                        catch { }

                        //Create NewFrame event handler
                        //(This one triggers every time a new frame/image is captured
                        videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(videoSource_NewFrame);

                        //Start recording
                        videoSource.Start();
            }

        }

        void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            //Cast the frame as Bitmap object and don't forget to use ".Clone()" otherwise
            //you'll probably get access violation exceptions
            pictureBoxVideo.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Stop and free the webcam object if application is closing
            if (videoSource != null && videoSource.IsRunning)
            {
                videoSource.SignalToStop();
                videoSource = null;
            }
        }

    }
}

I hope this tutorial helped you and that you now are also been able to use successfully webcams and other video recording sources in C#.  Should you have any questions, comments or suggestions, so just send me a comment.

15 Comments

  1. Sandysays:

    Hello Raffi,

    I have tried your code and it seems to work like a charm. My only requirement is to set the videosource to the windows forms size which means that the camera should open in a full window mode on the start. I am looking at the code snippet here but not able to change. Please can you help me out.

    try
    {
    //Check if the video device provides a list of supported resolutions
    if (videoSource.VideoCapabilities.Length > 0)
    {
    string highestSolution = “0;0”;
    //Search for the highest resolution
    for (int i = 0; i Convert.ToInt32(highestSolution.Split(‘;’)[0]))
    highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + “;” + i.ToString();
    }
    //Set the highest resolution as active
    videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(‘;’)[1])];
    }
    }
    catch { }

    //Create NewFrame event handler
    //(This one triggers every time a new frame/image is captured
    videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(videoSource_NewFrame);

    //Start recording
    videoSource.Start()

    • videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(‘;’)[1])];
      }
      Change this into
      videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(‘;’)[128])];
      }
      or set it high if you want

  2. Hey Raffi,

    That’s an awesome solution! Thanks for this really easy and great way to record from a webcam in C#. It works.

    Not so long ago I’ve needed a solution to handle cameras. The hard part was to stream to multiple locations (smartphones and PCs as well). After some searching I’ve found an SDK that enables to build an Onvif video server (www.camera-sdk.com/p_23-onvif-video-server-for-ip-cameras-and-webcams-onvif.html) in C#. It made it possible to display the image of my CANYON CNR-WCAM43G1 web camera on remote laptops and Android phones using RTSP streaming. It’s as if I had turned my USB webcam into an ONVIF camera. If you’re interested in this issue, I can recommend you this solution.

  3. Davidsays:

    Hi Raffi and anyone else reading this blog,

    I thought about my issue (grey/blue screen, no image) and I realised it was probably a resolution issue. Sure enough I hard coded highestSolution = “800;5”; and bingo everything works. thank you Raffi for an excellent code snippet.

    David

  4. Davidsays:

    Hi Raffi,

    Are you aware of any issues running your code in VS201? I have created a winforms application in VS 2012. Initially i targeted framework 4.0 but I have also tried 2.0. Everything runs but I get a picture with just noisy grey/blue rather than an image. I have checked that the event handler is executing and also that there is only one device.
    Any pointers would be very welcome and gratefully received

    David

  5. Balusays:

    Hello,

    Thanks for the nice artcile.. I have tried this.. it is working fine..
    My question is, I don’t want to display the video in the form, I want send this stream to HTML5. How can I do that?
    I have already connected to C# app using websockets.
    I also tried sending bitmaps as base64string, but it is flickering while displaying (little delay between frame to frame). Please suggest me how to stream video to html5 page.

    thank you

  6. elad_kcidsays:

    hi! i’ve done an application, using your tutorial, everything compile and run succesfully, but image in picturebox don’t appear, what can be the matter? thank you

    • Hm… have you tried to set up a breakpoint in the VideoCaptureDevices loop and see if there is more than one device? Maybe your webcam is the second device. Also set up a breakpoint at the NewFrame-event and see if it is triggered.

      • elad_kcidsays:

        Hi!
        Somehow, Form1_Load event hadn’t been called. I changed name of Form1_Load function and called it right after InitializeComponent() function.
        Now, everything works great.
        Thank you, very much for tutorial and response!

        • Nilosays:

          Can you send me a code snippet that shows how you did this. As I learn C# on my own, I cannot resolve the issue where the Form1_Load event is not being called.

          Thanks

  7. Bozidarsays:

    i will try but pls, give me some code

  8. Bozidarsays:

    But how i can make to save a record of webcam in my comp.

    • Hello Bozidar,
      you could save the images to your hard drive and then use C#’s Process.Start() function to call ffmpeg with parameters to build a video file from the images.
      Another quick and dirty way would be to create an MJPEG stream from the single images.

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked