Click here to Skip to main content
13,198,068 members (90,805 online)
Click here to Skip to main content
Add your own
alternative version


219 bookmarked
Posted 18 Aug 2006

WebCam Fast Image Capture Service using WIA

, 17 Aug 2006
Rate this:
Please Sign up or sign in to vote.
Grab frames from any webcam, transfer frames using WebServices, super easy and super fast
Sample Image - WebCamService.jpg

Update #1

  • I have added Directx to obtain cameras that did not show up using WIA. You may download the source code from Sourceforge.
  • Minimized delay at startup.
  • Even though it was pretty fast to grab a frame, it is now a little faster.
  • I have also added the ability to continuously grab frames from camera (delegates and timers).
  • I have not documented most of my code, but I will very soon (Sorry).
  • For the next update, you should be able to multicast images on your network. I am actually testing it right now. I have to say it works really well.

Please let me know if you run into any bugs or if you have any questions. I would be happy to help you.


For a long time, I have been looking for a good way to capture images without too much trouble. All you need to do is call one method to get the image.

I have used Windows Image Acquisition (WIA) to capture images. WIA provides a great deal of compatibility with webcams already running on Microsoft Windows XP.

This is my first posting on The Code Project, please do not hesitate to comment or give any suggestions. I would be very thankful if you provide any feedback.


Improved Image Capture Technologies: WIA

Windows XP supports still-image devices through Windows Image Acquisition (WIA), which uses the Windows Driver Model (WDM) architecture. WIA provides robust communication between applications and image-capture devices, allowing you to capture images efficiently and transfer them to your computer for editing and use.

WIA supports small computer system interface (SCSI), IEEE 1394, USB, and serial digital still image devices. Support for infrared, parallel, and serial still-image devices—which are connected to standard COM ports—comes from the existing infrared, parallel, and serial interfaces. Image scanners and digital cameras are examples of still image devices. WIA also supports Microsoft DirectShow®-based webcams and digital video (DV) camcorders to capture frames from video.

Windows Image Acquisition Architecture

WIA architecture is both an Application Programming Interface (API) and a Device Driver Interface (DDI). The WIA architecture includes components provided by the software and hardware vendor, as well as by Microsoft. Figure 1 below illustrates the WIA architecture.

Figure 1: The components of WIA architecture.
Figure 1: The components of WIA architecture.

Click here to see full-sized image.

The DLL Fix

I have included all the required references in the source code. You don't need to do this, but if you wish to know how you may read this section.


You want to add a reference to Microsoft Windows Image Acquisition type library.


You also want to add a reference to WiaVideo Type Library. However, after some trouble I read about a bug and its fix that occurs while importing the type library.

Use ILDASM to dump the type library Interop.WIAVIDEOLib.dll, then use Notepad to replace occurrences of valuetype _RemotableHandle& to native int. Then compile the iL dump file you fixed using ILASM in the CMD ilasm /DLL Add a reference to the new DLL and you are set to go.

The Code

Please keep in mind that the first image you take will initialize the camera. The initialization process takes a few seconds. You may notice the Join(3000) I added when activating the webcam. I added the join in order to avoid exceptions and allow enough time for the camera to do its thing. It was necessary to use the join. I think this delay is because USB protocol is slow or maybe it is just my camera. After the first image is taken, images start flying so fast it is going to look like a live video feed!!

using System;
using System.Collections.Generic;
using System.Text;
using WIALib;
using WIAVIDEOLib;
using System.Runtime.InteropServices;
namespace WebCamLibrary
    /// <span class="code-SummaryComment"><SUMMARY></span>
    /// This Class will initialize the camera using Windows Image Acquisition (WIA).
    /// Also, provides methods to view all connected cameras, capture single frame.
    /// <span class="code-SummaryComment"></SUMMARY></span>
    public class WebCam
        private static WebCam WebCamObj;
        /// <span class="code-SummaryComment"><SUMMARY></span>
        ///  variables needed 
        /// <span class="code-SummaryComment"></SUMMARY></span>
        private WIAVIDEOLib.WiaVideo WiaVideoObj;
        private WIALib.Wia WiaObj;
        private WIALib.DeviceInfo DefaultDevice;
        private WIALib.DeviceInfo[] Devices;
        private bool DeviceIsOpen;
        /// <span class="code-SummaryComment"><SUMMARY></span>
        /// Initialize The WebCam Class
        /// <span class="code-SummaryComment"></SUMMARY></span>
        private WebCam()
            DeviceIsOpen = false;
        /// <span class="code-SummaryComment"><SUMMARY></span>
        /// Please use this method to create a WebCam Object.
        /// <span class="code-SummaryComment"></SUMMARY></span>
        /// <span class="code-SummaryComment"><RETURNS>WebCam Object</RETURNS></span>
        public static WebCam NewWebCam()
            if (WebCam.WebCamObj == null)
                WebCam.WebCamObj = new WebCam();

            return WebCam.WebCamObj;
        private void Initialize()
            if (this.WiaObj == null)
                this.WiaObj = new WiaClass();
            if (this.WiaVideoObj == null)
                this.WiaVideoObj = new WiaVideoClass();
                this.WiaVideoObj.ImagesDirectory = System.IO.Path.GetTempPath();
        /// <span class="code-SummaryComment"><SUMMARY></span>
        /// Use it to close any open resources.
        /// <span class="code-SummaryComment"></SUMMARY></span>
        public void CloseResources()
                if (WiaObj != null)
                if (WiaVideoObj != null)
                if (DefaultDevice != null)
                if (Devices != null)

                DeviceIsOpen = false;
            catch (Exception e)
        private void SetDefaultDevice()

            System.Collections.Generic.List<WIALIB.DEVICEINFOCLASS> devs = 
                                        new List<DEVICEINFOCLASS>();
            WIALib.Collection devsCol = 
                            this.WiaObj.Devices as WIALib.CollectionClass;
            foreach (object obj in devsCol)
                WIALib.DeviceInfoClass dev = (WIALib.DeviceInfoClass)
                  obj, typeof(WIALib.DeviceInfoClass));
                if (dev.Type.Contains("Video") == true)
            Devices = devs.ToArray();
            if (Devices.Length > 0)
                DefaultDevice = Devices[0];
                throw new Exception("No Cameras Detected");

        /// <span class="code-SummaryComment"><SUMMARY></span>
        /// Get Connected Cameras
        /// <span class="code-SummaryComment"></SUMMARY></span>
        /// <span class="code-SummaryComment"><RETURNS>string[] contains names of connected cameras</RETURNS></span>
        public string[] GetConnectedCameras()
            string[] devs = new string[this.Devices.Length];
            for (int i = 0; i < devs.Length; i++)
                devs[i] = this.Devices[i].Name;
            return devs;
        private void CloseDefaultDevice()
            if (this.DeviceIsOpen == false)
                if (this.WiaVideoObj != null)
                    DeviceIsOpen = false;
            catch (Exception e)
                DeviceIsOpen = false;
        /// <span class="code-SummaryComment"><SUMMARY></span>
        /// Use this method to set the camera to capture 
        /// from if you have more than one camera.
        /// <span class="code-SummaryComment"></SUMMARY></span>
        /// <param name="name" />Name of the camera device.
        /// Get name from GetConnectedCameras() </param />
        /// <span class="code-SummaryComment"><RETURNS></RETURNS></span>
        public bool SetDefaultDevice(string name)

            for (int i = 0; i < Devices.Length; i++)
                if (Devices[i].Name.Equals(name))
                    DefaultDevice = Devices[i];
                    return true;
            return false;
        private bool OpenDefaultDevice()

                this.WiaVideoObj.PreviewVisible = 0;
                                                       IntPtr.Zero, 0, 0);
                this.DeviceIsOpen = true;
            catch (Exception e)
                return false;

            return true;
        /// <span class="code-SummaryComment"><SUMMARY></span>
        /// Use it to grab a frame. Use System.IO.MemoryStream to load image
        /// <span class="code-SummaryComment"></SUMMARY></span>
        /// <span class="code-SummaryComment"><RETURNS>byte array of the captured image</RETURNS></span>
        public byte[] GrabFrame()
            string imagefile;
            this.WiaVideoObj.TakePicture(out imagefile);
            return ReadImageFile(imagefile);
        private byte[] ReadImageFile(string img)
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(img);
            byte[] buf = new byte[fileInfo.Length];
            System.IO.FileStream fs = new System.IO.FileStream(img, 
            fs.Read(buf, 0, buf.Length);
            return buf;
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebCamService : System.Web.Services.WebService
    private WebCamLibrary.WebCam cam;

    public WebCamService()
        //Uncomment the following line if using designed components 
        cam = WebCamLibrary.WebCam.NewWebCam();      
    public byte[] GrabFrame() {
        return cam.GrabFrame();
    public string[] GetConnectedCameras()
        return cam.GetConnectedCameras();

Future Features

  • Redo this article, I don't think I did a very good job because its 6:00 am -> bedtime.
  • I would like use my other project to be able to broadcast images over the network(multicasting).
  • Look into possible compression technologies.
  • I think it would be great to transfer Images over UDP using smallest headers possible.
  • WebControl for Handheld devices to view camera images over the Web.


Fixed article layout


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Oz Jundi
Engineer TECO GROUP - Jundi Electrical Industry
United States United States
if you have any questions please send an email :

ojundi @ [%s].info

Oz [Jundi]

You may also be interested in...


Comments and Discussions

Questionwebcam script(s) Pin
Joachim Wegener4-Jun-17 9:19
memberJoachim Wegener4-Jun-17 9:19 
QuestionHow do I get images on OS startup Pin
Member 1138819914-Apr-15 1:26
memberMember 1138819914-Apr-15 1:26 
QuestionNOT WORK Pin
Member 1085208330-May-14 2:30
memberMember 1085208330-May-14 2:30 
QuestionBad Sample ... Avoid Pin
Steveo1237-Mar-14 9:36
memberSteveo1237-Mar-14 9:36 
SuggestionThank you for your article! I would like to recommend my new Camera_Net Library Pin
free5lot29-Dec-13 21:15
memberfree5lot29-Dec-13 21:15 
QuestionSample Not Working Pin
Member 1018922415-Aug-13 21:14
memberMember 1018922415-Aug-13 21:14 
AnswerRe: Sample Not Working Pin
Shambhoo kumar16-Sep-13 20:07
professionalShambhoo kumar16-Sep-13 20:07 
Questionconvert code 2 Pin
NanoParedaz5-Aug-12 19:11
memberNanoParedaz5-Aug-12 19:11 
QuestionHow can i get CAPTURE event via WIA ? Pin
peter lee sh22-Apr-12 19:11
memberpeter lee sh22-Apr-12 19:11 
Questionusing in Pin
yasoo8317-Jan-12 5:28
memberyasoo8317-Jan-12 5:28 
Questioni need a help Pin
sdurgeshs10-Sep-11 3:08
membersdurgeshs10-Sep-11 3:08 
QuestionWIA compatible webcams? Pin
jeremylow18-Mar-11 23:23
memberjeremylow18-Mar-11 23:23 
AnswerRe: WIA compatible webcams? Pin
Albert van Peppen3-Mar-12 8:02
memberAlbert van Peppen3-Mar-12 8:02 
GeneralClass not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)) at WIAVIDEOLib.IWiaVideo.CreateVideoByName Pin
olgaquecano30-Sep-10 0:42
memberolgaquecano30-Sep-10 0:42 
GeneralExcellent Pin
tandahunter28-Apr-10 21:52
membertandahunter28-Apr-10 21:52 
GeneralHelp!!! Pin
dustinkbaker21-Dec-09 5:45
memberdustinkbaker21-Dec-09 5:45 
AnswerRe: Help!!! Pin
Member 370561816-Mar-11 11:24
memberMember 370561816-Mar-11 11:24 
Generalgrab the frame to disk and read....... not good idea Pin
reborn_zhang5-Dec-09 23:54
memberreborn_zhang5-Dec-09 23:54 
GeneralMy vote of 1 Pin
criollo02-Dec-09 18:47
membercriollo02-Dec-09 18:47 
GeneralMy vote of 1 Pin
Priyank Bolia13-Nov-09 4:57
memberPriyank Bolia13-Nov-09 4:57 
QuestionIt seems many errors there? Pin
satigv1-Apr-09 0:11
membersatigv1-Apr-09 0:11 
GeneralInside a thread Pin
brousse12326-Mar-09 2:01
memberbrousse12326-Mar-09 2:01 
GeneralRe: Inside a thread Pin
brousse12326-Mar-09 8:15
memberbrousse12326-Mar-09 8:15 
QuestionError using the code "unable to connect to remote server" Pin
xicorete23-Feb-09 5:56
memberxicorete23-Feb-09 5:56 
GeneralI have Error In This Code Pin
Member 418227827-Jan-09 15:28
memberMember 418227827-Jan-09 15:28 
GeneralRe: I have Error In This Code Pin
Großvesir19-Feb-09 23:22
memberGroßvesir19-Feb-09 23:22 
QuestionUpdate for .Net 2.0+? Pin
williamhix21-Jan-09 4:34
memberwilliamhix21-Jan-09 4:34 
QuestionInitialize? Pin
Ton_B5-Jan-09 11:09
memberTon_B5-Jan-09 11:09 
AnswerRe: Initialize? Pin
Murlakatamus18-Jan-09 7:15
memberMurlakatamus18-Jan-09 7:15 
GeneralRe: Initialize? Pin
Ton_B18-Jan-09 8:39
memberTon_B18-Jan-09 8:39 
Questionhow to configure with iis Pin
amol gathale26-Nov-08 2:16
memberamol gathale26-Nov-08 2:16 
AnswerRe: how to configure with iis Pin
Murlakatamus10-Jan-09 6:14
memberMurlakatamus10-Jan-09 6:14 
GeneralRe: how to configure with iis Pin
tdson30-Oct-10 18:04
membertdson30-Oct-10 18:04 
GeneralConfused beginner Pin
bambrose10-Nov-08 11:52
memberbambrose10-Nov-08 11:52 
GeneralRe: Confused beginner Pin
Oz Jundi19-Jun-10 22:14
memberOz Jundi19-Jun-10 22:14 
Questioncode in C++ for controlling the maximum number of frames/sec [modified] Pin
stephen_77728-Oct-08 10:48
memberstephen_77728-Oct-08 10:48 
QuestionReleasing WebCam Resource : Pin
Ruchit Surati30-Sep-08 5:27
memberRuchit Surati30-Sep-08 5:27 
Questionvideo Pin
jajjssddd23-Sep-08 21:07
memberjajjssddd23-Sep-08 21:07 
jmeljurado15-Aug-08 9:30
memberjmeljurado15-Aug-08 9:30 
AnswerWindows Vista 64x Pin
Member 398699118-Jul-08 0:18
memberMember 398699118-Jul-08 0:18 
GeneralRe: Windows Vista 64x Pin
Yifeng Ding2-Sep-08 4:27
memberYifeng Ding2-Sep-08 4:27 
GeneralRe: Windows Vista 64x Pin
deunkel19-Apr-10 10:06
memberdeunkel19-Apr-10 10:06 
GeneralError HRESULT E_FAIL Pin
shama36-Jul-08 5:03
membershama36-Jul-08 5:03 
QuestionRe: Error HRESULT E_FAIL Pin
joshijimit9-Feb-10 22:53
memberjoshijimit9-Feb-10 22:53 
GeneralDirectShowLib missing Pin
nick716-May-08 18:53
membernick716-May-08 18:53 
GeneralRe: DirectShowLib missing Pin
Murlakatamus10-Jan-09 6:21
memberMurlakatamus10-Jan-09 6:21 
GeneralResolution Pin
Kloken24-Jan-08 1:14
memberKloken24-Jan-08 1:14 
GeneralGreat Library.....but.... Pin
paymahn17-Sep-07 22:44
memberpaymahn17-Sep-07 22:44 
GeneralRe: Great Library.....but.... Pin
shamaaaaaaaaaaaaaa26-Apr-08 8:16
membershamaaaaaaaaaaaaaa26-Apr-08 8:16 
GeneralRe: Great Library.....but.... Pin
shama36-Jul-08 5:07
membershama36-Jul-08 5:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171020.1 | Last Updated 18 Aug 2006
Article Copyright 2006 by Oz Jundi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid