Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » COM Interop » Catch a Snapshot via your webcam using C#: Part VII

Catch a Snapshot via your webcam using C#: Part VII

In this article, I will show how to catch a snapshot view from your personal web cam.

Author Rank :
Page Views : 45860
Downloads : 2361
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WebCam.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


One of the useful cases when COM is employed is when one profits of the already existed API, those developed within an environment other than .Net in order to leverage some operations that aren't possible via the managed code. A good example is the WIA API "wiaaut.dll". It represents a set of services that enable profiting of the devices services such as webcams, cameras and scanners.

Walkthrough :

You have to know that this kind of operation is only leveraged within windows XP environment, moreover, the WIA API is not automatically delivered with Windows; therefore, it must be downloaded from this link.

http://www.microsoft.com/downloads/details.aspx?FamilyID=a332a77a-01b8-4de6-91c2-b7ea32537e29&displaylang=en

First, install the WIA API by extracting the content of the zipped file then by copying and pasting the wiaaut.dll assembly to C:\Windows\System32 and finally by registering the assembly using the regsvc32.exe

Figure 1.

It is necessary to choose a peripheral therefore the library provides us the dialog box that enables the selection of peripherals through a list view. To use this dialog box you have to implement the following code :

        Device oDevice = null;
        CommonDialogClass oDialog = new CommonDialogClass();
        try
        {
            //This dispalys the dialog box that enables the user to choose the right device
            oDevice = oDialog.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);
        }
        catch (Exception caught) { }

Well, as I have only a webcam device the dialog box will look like the image shown in the figure2

Figure 2.

But you may say I can use this line

oDevice = new CommonDialogClass().ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false);

Instead of this one

oDevice = oDialog.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);

But I tell you that you will receive a runtime error in the first case.


Figure3

That means that the error occurs when the device you are trying to connect to is not WIA compatible. So it is worth to let the user select his/her device by him/her self.

To get the snapshot you may use this code :

Device oDevice;
        string jpegGUID;
        Item oItem;
        string path;
        //This lets the user select the correspondent device
        oDevice = new CommonDialogClass().ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false);
        /* As the image is of jpg format then you try to get the value of the representative GUID */
        RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"CLSID\{D2923B86-15F1-46FF-A19A-DE825F919576}\SupportedExtension\.jpg");
        jpegGUID = key.GetValue("FormatGUID").ToString();

The above is a kind of preparation because it allows selecting the correspondent device in first phase, then in a second phase; it retrieves the jpg registry reference in order to be used later.

In order to make a command and pass it to the device you may use this code :

try
{
    oItem = oDevice.ExecuteCommand(CommandID.wiaCommandTakePicture);
    // As you may remarque, the jpg registry reference is passed as an
    // argument at the transfer method level

     ImageFile imgFile = oItem.Transfer(jpegGUID) as WIA.ImageFile;
   /* This method render the user more familiar when precising the path
    As the save dialog box is used in this case */
    SaveImageAs();
    imgFile.SaveFile(path);
    oItem = null;
}
catch (Exception caught)
{
    MessageBox.Show("Put another image");
}
void SaveImageAs()
{
    SaveFileDialog dlg = new SaveFileDialog();
    dlg.Filter = "(*.jpg)|*.jpg";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        path = dlg.FileName;
    }
}

What if you want the represent those couples of codes in more representative and methodic way, you may create a class for this purpose and encapsulate the code within it as follow :

public class WebCam
{

  Device oDevice;
  string jpegGUID;
  Item oItem;
  string path { get; set; }
  public string GetSnapShotPath()
  {
            return path;
  }
 
  public WebCam()
  {
    try
     {
      //This lets the user select the correspondant device
      oDevice = new  CommonDialogClass().ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);
     //As the image is of jpg format then you try to get the value of the representative GUID
      RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"CLSID\{D2923B86-15F1-46FF-A19A-DE825F919576}\SupportedExtension\.jpg");
     jpegGUID = key.GetValue("FormatGUID").ToString();
    }
    catch (Exception caught)
    {
      MessageBox.Show("SnapShot canceled or something wrong!!!");
    }
  }
  //Via this method the snapshot method will be executed
  public void SnapShot()
  {
    try
    {
    oItem = oDevice.ExecuteCommand(CommandID.wiaCommandTakePicture);
    ImageFile imgFile = oItem.Transfer(jpegGUID) as WIA.ImageFile;
    SaveImageAs();
    imgFile.SaveFile(path);
    oItem = null;
    }
    catch (Exception caught)
    {
     MessageBox.Show("Put another image");
    }
  }
    //This methos lets the user set image path with a more familiar way
    void SaveImageAs()
    {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "(*.jpg)|*.jpg";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                path = dlg.FileName;
            }
    }
 }

Now, to consume this above class services, create a new windows application project then add a picture box, a button and a status strip then copy and paste the above class within the scope of the form code. The form should looks like in the figure 4



Figure 4.

Then, add a tool strip label as shown in the figure 5



Figure 5.

Afterward, implement the button stab with this below code :

private void button1_Click(object sender, EventArgs e)
        {
            WebCam oCam = new WebCam();
            oCam.SnapShot();
            pictureBox1.Image = Image.FromFile(oCam.GetSnapShotPath());
            toolStripStatusLabel1.Text = oCam.GetSnapShotPath();
        }

Try to run the application



Figure 6.

If you browse to the emplacement where the image was saved you will remark that a jpg file is newly added. In my case, it is, Of Corse, the great Pacmedi and I.



Figure 7.

And if I try to open the image, I will have as a result .



Figure 8.

Good Dotneting !!!
 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by swapnajeet choudhury on May 14, 2011

I m getting the following error when i try to run the sample.I could not find any interface to sort the problem.Please let me know what needs to be done


  Interop type 'WIA.CommandID' cannot be embedded. Use the applicable interface instead.  

  'WIA.CommandID' does not contain a definition for 'wiaCommandTakePicture'  
 [Top] Rate this article
 
 About the author
 
Bechir Bejaoui

The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT".

He also holds:

MCPD enteprise solutions developement 3.5 certification and MCTS distibuted application developement 2.0

 He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
konrad by low On January 23, 2009
hi, i am working on a c sharp project. MY project need to regonize the user faces in working hours period. Capture the user image. Must be able to detect and record down the user absence or presence period. Can some one help me ???
Reply | Email | Modify 
Link Down by Helio On February 18, 2009
Hi guys, i´m really need study this code, but the link is down. :( Someone can fix this ? Thanks a lot, cheers!!!

WebCam.zip
Reply | Email | Modify 
Tks by Helio On March 4, 2009
Tks a million, but not works here :( There are a problem with the object Device. Device oDevice; Help-me please!!! I'm so sad :(
Reply | Email | Modify 
for compliment by shiv On October 24, 2009
it's excellent code
Reply | Email | Modify 
Re: for compliment by Trinity On October 24, 2009
Not at all you're welcome ; )
Reply | Email | Modify 
nice article by Mohammed On November 20, 2009
Really useful.
Thanks so much
Reply | Email | Modify 
webcam by sherif On December 5, 2009
this is amazing man!!!
Reply | Email | Modify 
Re: webcam by Bechir On December 6, 2009
Oh I'm amazing now ho ho ho ho
Reply | Email | Modify 
Re: Re: webcam by soukat On April 12, 2011
can we preview using same the same in a picture box or panal
Reply | Email | Modify 
Catch a Snapshot via your webcam using C#: Part VII Project by Paul On January 6, 2010
Hi,
    Is the project code available for download? I have tried cut/paste into a new project but can't seem to build the project successfully.

Thanks
Paul.
Reply | Email | Modify 
RegistryKey by erubey On April 8, 2010
The registrykey type send me a mistake, and I can't find a librery or something to make it works. I'd be wonderfull if someone could help me.
Reply | Email | Modify 
about this project by bhrugesh On April 22, 2010
project works fine but i need to do somthing more with this project
i need to add "save as" button n also saved it on perfect dir with time n date stamp
what would i doo for further bec i m new in video streaming line i m tottaly confused maile me on brainscrew1983@gmail.com
at the end perfect project n also give me perfect description of it

Reply | Email | Modify 
exception by saurabh On May 25, 2010
Exception from HRESULT: 0x80210083

followed the way u said ..i m able to acess classes in wia namespace but this is the eroor when capture image method is called
Reply | Email | Modify 
not accessing by techmaniac On June 10, 2010
i got "Exception from HRESULT: 0x80210083" this error 
i have already used unspecifieddevice instead of cameradevice 
but it look same so help ASAP
fast fast
can it happen due to fact that i have no such devices connect to my pc
Reply | Email | Modify 
directive ? by Cell On June 21, 2010
Any directive to make this work ? It doesn't seem to know what Device and Item is.
Reply | Email | Modify 
windows 7 by Wessel On July 9, 2010
Thank you for this code.  Is there any help you can provide to make capturing a picture from a camera device on windows 7 possible?  I have searched the web high and low and found only dead ends.

Thanks you
Reply | Email | Modify 
i have an error by Kareem On August 25, 2010
iam using Canon camera
& i have an error in this line "oItem = oDevice.ExecuteCommand(CommandID.wiaCommandTakePicture);
"
the error is : the method or operation is not implemented

please any help about this ...

thanks ...
Reply | Email | Modify 
not working by prakash On October 23, 2010
sir,,,but this coding is not working in window 7...or i'm implementing the code wrong....can u pls send me some snaps and the correct way of implementing the code..sir i want this pls as quick as possible-   prakashgupta3@gmail.com(email-id)
Reply | Email | Modify 
Re: not working by Kareem On October 25, 2010
Hello Prakash :)

i think its not working with vista or win 7
but ill check it for you & ill replay at you asap :)

u can add me on Gmail (badprogramer@gmail.com)

Reply | Email | Modify 
Re: Re: not working by Bechir On October 25, 2010
Yes, because win 7 and vista are using another resources
Reply | Email | Modify 
Re: Re: Re: not working by Luis Alonso On February 9, 2011
I read your code, I am working in VS2010 on Windows 7, but there are lines of code give me error, could you help me? (I have VS2008)
Reply | Email | Modify 
Re: Re: Re: not working by Luis Alonso On February 9, 2011
I read the code, I'm working in VS2010 on Windows 7, there are some lines of code give me error, I could help. I have also installed vs2008
Reply | Email | Modify 
thanks by Mukesh On November 11, 2010
thanks for all above code and information It works for me just require to add few namespace.But it really works. Thanks once again
Reply | Email | Modify 
Error by Vandana On February 16, 2011
string path { get;set;} i got error on above line. i working on .net 2.0 plz help me out sir
Reply | Email | Modify 
Solution by Vandana On February 16, 2011
Thankx for ur code. i got solution
Reply | Email | Modify 
Device by Jasper On March 28, 2011
Hi, i can't create the DialogBox to select the device. Someone could tell me where i can find the device toolsbox... that will help me. Like Cell, I've got the problem with Device oDevice and Item oItem, i think because i haven't the device toolbox. Thx
Reply | Email | Modify 
error by anil On August 17, 2011
how to rectify the HRESULT error
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.