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
- A webcam. For example this one:
No products found.
- Basic C#-knowledge. If not exists, read this:
No products found.
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.
This is only showing the video.How to save the video in the computer?Please help me.
where the recording video file residing.
I tried this code in Visual Studio 2015 and there is a memory leak which appears to be fixed by adding a Dispose() method inside this event handler:
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
if (pictureBoxVideo.BackgroundImage != null)
{
pictureBoxVideo.BackgroundImage.Dispose();
}
pictureBoxVideo.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
}
This manifests itself by the image turning into a red box with an “x” in it after several seconds of running. The memory leak became apparent by looking at Visual Studio’s “Process Memory (MB)” chart in its “Diagnostic Tools” pane.
how to can we record audio as well as video
aforge unfortunately does not has audio functionality
Hi RAFFI!
I want to grab images from a particular camera.
I have tried for many times this solution, using one type of camera (Bonito Radient ecL), I followed all steps but nothing. I tried also to add MatroxImagingIntellicam dll files in the references as the dll file of the camera but nothing at all.
So, please Do you have any solution about that?
Thank you in advance for everyone who will support me in this project.
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
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.
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
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
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
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.
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!
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
Hi,
probably too late but for new readers. Go to the properties tab in the form and click on events. Scroll down to “LOAD” and (there should be an empty space) type in Form1_Load (If you’re only using one form).
Then when the form loads either via upon initialization or a button click pointing to the form, the camera will load
i will try but pls, give me some code
You could use the AviWrite Class from AForge libraries. Create an AviWriter instace and call the AddFrame method everytime a new frame is received from the webcam.
Sample code is over here:
http://www.aforgenet.com/framework/docs/html/5fedbbbe-6d28-5f69-35a2-9d7119544a2d.htm
If you need more help, tell me. :)
Still not successfull, i made it but i got one line which is failing down in test.avi
what should i do?
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.