jump to navigation

Webcam in C#: AForge.NET March 21, 2009

Posted by haryoktav in Taipei.
trackback

AForge.NET is another C# framework to do image processing and others. For further information just go to http://www.aforgenet.com/framework/

Here, I want to show you how to access webcam using AForge libraries. I found that these libraries are more complete and so far work for me.

I can select one of webcams attached in my notebook (a notebook usually has a webcam and I connected another USB webcam). And wow, awesome!

Now, download and extract the AForge libraries from http://www.aforgenet.com/framework/downloads.html, download this project here (using VS2005, don’t forget to change the extension from “.doc’ to “.rar”).. and I hope that you will have fun with your webcam(s).

Also, remember to Add Reference for AForge.Video.dll and AForge.Video.DirectShow.dll into the project.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

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

namespace cam_aforge1
{
    public partial class Form1 : Form
    {
        private bool DeviceExist = false;
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoSource = null;

        public Form1()
        {
            InitializeComponent();
        }

        // get the devices name
        private void getCamList()
        {
            try
            {
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                comboBox1.Items.Clear();
                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                DeviceExist = true;
                foreach (FilterInfo device in videoDevices)
                {
                    comboBox1.Items.Add(device.Name);
                }
                comboBox1.SelectedIndex = 0; //make dafault to first cam
            }
            catch (ApplicationException)
            {
                DeviceExist = false;
                comboBox1.Items.Add("No capture device on your system");
            }
        }

        //refresh button
        private void rfsh_Click(object sender, EventArgs e)
        {
            getCamList();
        }

        //toggle start and stop button
        private void start_Click(object sender, EventArgs e)
        {
            if (start.Text == "&Start")
            {
                if (DeviceExist)
                {
                    videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
                    videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
                    CloseVideoSource();
                    videoSource.DesiredFrameSize = new Size(160, 120);
                    //videoSource.DesiredFrameRate = 10;
                    videoSource.Start();
                    label2.Text = "Device running...";
                    start.Text = "&Stop";
                    timer1.Enabled = true;
                }
                else
                {
                    label2.Text = "Error: No Device selected.";
                }
            }
            else
            {
                if (videoSource.IsRunning)
                {
                    timer1.Enabled = false;
                    CloseVideoSource();
                    label2.Text = "Device stopped.";
                    start.Text = "&Start";
                }
            }
        }

        //eventhandler if new frame is ready
        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap img = (Bitmap)eventArgs.Frame.Clone();
            //do processing here
            pictureBox1.Image = img;
        }

        //close the device safely
        private void CloseVideoSource()
        {
            if (!(videoSource == null))
                if (videoSource.IsRunning)
                {
                    videoSource.SignalToStop();
                    videoSource = null;
                }
        }

        //get total received frame at 1 second tick
        private void timer1_Tick(object sender, EventArgs e)
        {
            label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
        }

        //prevent sudden close while device is running
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseVideoSource();
        }
    }
}

Snapshots:

Select webcam source

Select webcam source

Seeing into the monitor...

Seeing into the monitor…

Comments»

1. tiberius - May 28, 2009

how can i get the webcam resolution?

haryoktav - June 2, 2009

#tiberius
sorry, i haven’t tried yet.. ^^

2. Samo - June 17, 2009

hello! I have one question! Where can i get text box for camera? I wrote this code in my program, but on the form I nothing saw.
thanks for help

3. haryoktav - June 19, 2009

#samo
do you mean the text “Device ready” and “Device running”?
I used a “label” to print those messages, and put it inside a “groupbox” for pretty interface 🙂
this line will change the label: label2.Text = “Device running…”;
you can download the project from the link above
thx.

4. jason - July 5, 2009

The Combo Box is empty? or i have to change the text to USB video device

5. sebastian - July 17, 2009

no me devuelve la imagen al picture, creo que el problema esta en
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);

Porque puede llegar a ser?

6. David - July 26, 2009

do you have any codes to view the real video of usb web camera in web browser when running your codes? thanks in advance.

7. [AAA] - July 26, 2009

Thanks very much.

I’ve tested, It’s works!!

8. haryoktav - August 5, 2009

#jason
If there is no USB camera device installed then the combo box will empty

#sebastian
Estoy de acuerdo con usted
pero no tengo ni idea sobre esto

#david
wow, that is beyond of me this time ^^
I ever heard about IP-Camera and we can access it using MJPEG (Motion JPEG). You can search in http://www.codeproject.com how to access MJPEG.
Or using another ways ^^
Ganbatte kudasai !

#AAA
thanks!

9. donny - August 30, 2009

Hi… Hary,,
I have make LAN chat application. But how to combine your webcam in my application?
Thanks

10. prazetyo - September 1, 2009

Hi…

I’ve making Lan Chat application in C#, but how to add Webcam feature?

Thanks

11. Jay - September 28, 2009

Hey haryoktav,

Thanks for this post, you saved me a lot of time.

12. haryoktav - September 29, 2009

#donny. prazetyo
sorry, that is beyond mine for now.. ^^

#Jay
my pleasure..

13. Osama - October 8, 2009

can any one plz help ..
i ve a project named: Cursor control through mouse movement in which i have to initiallize webcam n capture stream of images of the user so that i can process that image to find the centre of the user’s eye..

plz help me to initiallize webcam n in taking input stream of images ..

14. Lulu - October 27, 2009

Hi haryoctav,
thank you for the code, never got a webcam picture so fast in a project.
I added some useful code to show the camera property dialog (from the camera driver). Create a new button and the following handler code:

private void props_Click(object sender, EventArgs e)
{
if (videoSource != null)
{
videoSource.DisplayPropertyPage(this.Handle); // modal dialog
//videoSource.DisplayPropertyPage(IntPtr.Zero); // non-modal
}
}

After starting the webcam, this dialog can be shown.

But until now I found no way to get possible resolution and framerate settings from the driver. Any suggestions?

15. Jordan - November 7, 2009

when i use this even though i have the DesiredFrameSize set to 160,120 it is only showing the top left portion of what my webcam is seeing, i cant get it to resize and show all of what my webcam is seeing, any ideas?

16. mohammed Bakhit - December 20, 2009

hi,

Can anyone help me to use yahoo messenger dll’s in my codings for creating video&audio conferencing using C#.net….if possible please send me links to m.bakhit@yahoo.com

Thank you

17. Waqar - December 26, 2009

Thanks alot man…

This was a real time saver, and the code is also not that hard understand..

Regarding the Video Resolution, its just about keeping the Desired Frame Size according to the picture box size.

I set it to 500 x 400
videoSource.DesiredFrameSize = new Size(500, 400);

And Make the ‘PictureBox’ size bigger in the Design View of your Application. Works Perfectly.

Cheers…………..

18. Girish - January 15, 2010

How do i save picture which we have captured.Please help.

19. Utilizando la webcam en C# con el Framework AForge — 0×1FEE3 - January 18, 2010

[…] Aquí les dejo donde aprendí como hacerlo: https://haryoktav.wordpress.com/2009/03/21/webcam-in-c-aforgenet/ […]

20. dhoto - February 15, 2010

Mantab,…

21. Adit - February 22, 2010

Salam knal mas..^_^
bagus tutorialnya…
tapi saya dapat error di :
if (videoSource.IsRunning) <– NullReferenceExeption was unhandeled
Object reference not set to an instance of an object.

kenapa ya kira2 mas??

22. haryoktav - February 24, 2010

#dhoto
thanks man!

#Adit
variable videoSource-nya kosong/null, mustinya sudah dicek oleh baris sebelumnya.. tapi kok tembus ya.. aneh..

#others
sorry for leaving aForge long time ago..
i hope you already have solutions

23. lee - February 26, 2010

i face this problem. So how can i solve that?
1. visual studio cannot start debugging because the debug target ‘.exe’ is missing….

2. The name “timer1″does not exist..

24. lee - February 26, 2010

now both problem is solve which i mention just now.. But now the combo box never show any device selection (it’s blank). So how can i solve it? please please… 😦

25. Dida - March 7, 2010

Bang.. saya mau tanya nih.. gimana ya cara biar dapet fps bagus..

Saya set desired frame ratenya (380,437) ngikutin picture boxnya..
cuma dapet 1 fps persecond.. kok kecil banget ya.. ada suggestion ga gimana biar bisa naekin fps nya.. skitar 10++ fps..

Terima Kasih sebelumnya..

26. Adit - March 10, 2010

setelah di coba2 ini dia “&Start” gak usah pake “&” baru berjalan…^_^
makasih banyak mas…
saya lagi bikin penggerak pointer pake camera dengan menggunakan color filtering (AForge juga)…
sharing2 lagi ya..
lanjutkan….

27. Lara - April 21, 2010

what muss I do in
//do processing here
???

28. haryoktav - May 1, 2010

#Lara
put your image processing algorithms..

29. lucky - June 16, 2010

can u make a program that put iris cordinates on the screen..??????
please contact @ lucky_xxxxx@yahoo.xxx

30. haryoktav - July 4, 2010

#lucky
sorry I am in a busy recently. in fact, i haven’t used AForge already..

31. arif nasution - August 21, 2010

thank you for your help
it’s work

32. Richard - August 27, 2010

Hi we want to save to avi file.

The AviWriter is documented, but it does not exist in AForge. There is no example anywhere of saving to avi file. or any file.

33. majid baig - October 31, 2010

any 1… plz tell me that how can i access ip camera using AForge .net using MJPEG??????
its urgent brothers….. i need it as soon as possible…!

34. jibin - November 1, 2010

HI,
is there any way to get audio uisng Aforge and stream the captured audio after encoding it….
Pls help if posssible give me some links of examples

Thanks
JIbin

35. Predrag - November 9, 2010

If you are interested in this topic be sure to check out this article: http://www.codeproject.com/KB/miscctrl/webcam_c_sharp.aspx

36. circass - November 11, 2010

Hi,
code works for a usb twain webcam but does not work for firewire cam. Is there a solution for that ?

37. Craig - February 5, 2011

Hi

Using this code, how could I have a still image of the same webcam display in another picturebox?

38. Craig - February 6, 2011

Hi again….never mind the last post, I sorted it!

39. gf - March 5, 2011

Hi Haryoktav!

I have everything working except there is no picture! I know my cam works (using Skype, e.g.), I know the timer works, I get frames rates, etc.

I had the same problem using another aforge example.

Help!

-gf

40. Souhir Sghaier - March 13, 2011

Please after the download of the framwork AForge.NET where can I put it? How can I execute this code??

41. Marius - March 16, 2011

Thx, it help me.

42. halit - March 30, 2011

hi,this application not work is vs 2010 ide,and nothing warning in the vs 2010 ,you can help me ,i wait your advices as soon as

43. Work with Web cam - July 6, 2011

[…] […]

44. Fady Khafagy - July 14, 2011

Can you convert to asp.net i had been converted but no devices found although it working very well as windows App.

45. hullo909 - October 16, 2011

Hey haryoktav,
I’m completely new to visual C#. I’ve tried to copy-paste your code into a new windows form project in visual c#. When I run the program, it shows many errors like:

1: The type or namespace name ‘Form1’ could not be found (are you missing a using directive or an assembly reference?)

2: The name ‘comboBox1’ does not exist in the current context

etc.
There are many more suggesting the same for label 2, start, timer1 and picturebox1.

Can you help me with this and suggest how I must proceed from here?

thanks a lot…

46. Adhiraj - January 8, 2012

i tried out your code..while it shows error

Error 1 The type or namespace name ‘Form1’ could not be found (are you missing a using directive or an assembly reference?) C:\Users\shaji c v\AppData\Local\Temporary Projects\WindowsFormsApplication1\Program.cs 18 33 WindowsFormsApplication1
??.. what do i do??

47. Madiha Anwer - February 9, 2012

hOW TO INCLUDE afroge library in c# …..

48. andrei - March 3, 2012

Hi man,
i tried to convert the code for asp.net. Actually the WebCam was found but the events for example “NewFrame” wasn’t calling.

Have you any ideia, how can i convert this code to asp.net?

Regards,
Andrei Silva

49. anas - March 9, 2012

Hello ,,
may my question not here 🙂
I build an application in c# that display a stream of image from the mobile(like webcam) and I want this application appear as an option inside the MSN or Skype
what is the best way
thanks for the help

50. Ashish yadav - March 13, 2012

PLZ anyone can tell me , how to save picture in AFORGER.net
after capturing it . becouse i would like to compare it with next pic .
PLZ do help me

51. Eng.Dany Wehbe - March 13, 2012

thank you very much,it worked perfectly for me
thanks for your effort and thanks to AForge.Net

52. lpt - March 17, 2012

I have the problem of not getting any detected devices in the combo box, it remains empty! Debugging the code does’nt give any errors though. Help will be much appreciated. Thanx!

53. yousuf khan - April 21, 2012

how to select Add Reference and Aforge.video

54. ashish - June 19, 2012

just download AForge and than place that folder in you app. folder ,than add reference + ………

55. bazli - August 18, 2012

guys, copy and paste others program is not recommended for a beginner, he just share with us the code but its our initiative to learn from basic, if we copy and paste the program in c# then for sure will have error cause the interface we havent created and the directory willnot be same, we must do fro scratch

56. Kevin K - August 21, 2012

Thanks a lot worked just perfect!

57. lia - December 13, 2012

i search in google long time just to search how i can save my video capture to directory.. please help me, any sugestioon?? with c# and AForge.net

58. M. YILDIRIM - January 14, 2013

Respect++ 🙂 A good kick-start for beginners 🙂 Thanks.

59. Ved - February 18, 2013

I just implemented evrything…..but unable to resolve following error==>
1. NewFrameEventHandler in line :
——————————————————————————–
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);

2. NewFrameEventArgs eventArgs in line:
———————————————————————————
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)

60. www.teampages.com - June 14, 2013

I for all time emailed this webpage post page to all my contacts, because if like to read it after that my links will too.

61. Aris - June 28, 2013

NewFrameEventArgs – error – you should add references A.Forge.Video…. This solves it forme

62. erum jamal - July 19, 2013

when i run this code following error occur please help me in this regards as soon as possible

An unhandled exception of type ‘System.NullReferenceException’ occurred in camera_capture.exe

Additional information: Object reference not set to an instance of an object.

63. orbit6 - November 7, 2013

Nice post men, Im was just looking for something like this :). It herlp me a lot

64. Melito Fernandes - March 19, 2014

It would be real helpfu if any one if u can solve me these :

1) how can i capture the image from the video using the code above?
2)where will the image be saved and how can i view it? i mean in a folder on my computer or il b required to make a database for the same ?
3)if i need to capture the video currently running and save them every 15 minutes then plz help …

Thanks in advance ..

65. cahit - May 1, 2014

Hi guys
How can I save to real camera like video ?

66. reallifecam com view 03_1 - May 30, 2014

obviously like your website however you have to take a look at the spelling
on several of your posts. Several of them are rife with spelling issues and I in finding it
very bothersome to inform the reality nevertheless I’ll surely come
back again.

67. Simon Ed - October 17, 2014

65. cahit! Hi! I read your question, and it’s possible that this sample help you to solve your problem. You can try the sample here: http://www.camera-sdk.com/p_52-how-to-record-audio-and-video-stream-into-mpeg-4-onvif.html

Besides that you can find more useful information how can you save your camera’s video like a video and how can you take a snapshot.

68. samuelagm - January 15, 2015

Thanks alot, it worked well

69. Waleed Butt - February 24, 2015

Hi
Can you please tell me that Is there a way to turn off the flash light of laptop camera using Aforge.Net framwork?
If so then please tell me asap.

70. Shayan Ali - March 16, 2015

Hello ! Great work. I am trying this in VS2008 for Windows CE but it gives me 2 errors in

private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
System.Drawing.Bitmap img = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = img;
}

Error 1 The type ‘System.Drawing.Bitmap’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’. C:\Users\shayan\Documents\Visual Studio 2008\Projects\WinCE_Webcam_Project\WinCE_Webcam_Project\Form1.cs 65 13 WinCE_Webcam_Project

Error 2 ‘System.Drawing.Bitmap’ does not contain a definition for ‘Clone’ and no extension method ‘Clone’ accepting a first argument of type ‘System.Drawing.Bitmap’ could be found (are you missing a using directive or an assembly reference?) C:\Users\shayan\Documents\Visual Studio 2008\Projects\WinCE_Webcam_Project\WinCE_Webcam_Project\Form1.cs 64 65 WinCE_Webcam_Project

Please tell how to get rid of them ?

71. A - April 13, 2015

+1 for the question on AForge being able to turn webcam LEDs on and off. A bit of searching says this seems to be possible, but only with certain cameras:

http://www.aforgenet.com/framework/docs/html/aed2bddb-f36b-4233-96ac-935e8f66615c.htm

72. Absar Ahmed - November 10, 2015

Asalam o alikum, hi hellow can any one help me
i want to just code of webcam using c# or if any have project which is running so please send me at absar_ahmed15@outlook.com but webcam should be autoplay no need to start with button
thanking you,

73. Juchan - March 23, 2016

Thank you very much~!!!
So very easy~!

74. Agung Alfredo - May 12, 2017

thank in advance

75. Boxing - August 29, 2017

I do trust all the ideas you’ve offered in your post.
They are very convincing and can certainly work.
Still, the posts are very quick for starters. Could you please extend them a little from subsequent time?
Thanks for the post.

76. Vince - September 7, 2020

Hello i encountered an error:

An unhandled exception of type System.NotSupportedException occurred in AForge.Video.dll Additional information: No devices of the category

Can anyone help me . thanks


Leave a comment