Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Total page views :  20727
Total downloads :  1110
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WebCam.zip
 
Become a Sponsor


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 !!!
 


Login to add your contents and source code to 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'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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WebCam.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | 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 | Delete | Modify | 
for compliment by shiv On October 24, 2009
it's excellent code
Reply | Email | Delete | Modify | 
Re: for compliment by Trinity On October 24, 2009
Not at all you're welcome ; )
Reply | Email | Delete | Modify | 
nice article by Mohammed On November 20, 2009
Really useful.
Thanks so much
Reply | Email | Delete | Modify | 
webcam by sherif On December 5, 2009
this is amazing man!!!
Reply | Email | Delete | Modify | 
Re: webcam by Bechir On December 6, 2009
Oh I'm amazing now ho ho ho ho
Reply | Email | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.