Take a picture automatically using a webcam in C# using WIA

Micael picture Micael · Nov 29, 2010 · Viewed 12.4k times · Source

I'm using WIALib to access my webcam. The code I'm developing is pretty simple: when a button is pressed a webcam picture is taken, and then displayed in a picture box.

I can already take pictures with my webcam, but it isn't yet fully automated. The only way I found to retrieve the pictures taken by the webcam, is using this:

wiaPics = wiaRoot.GetItemsFromUI( WiaFlag.SingleImage, WiaIntent.ImageTypeColor ) as CollectionClass;

But this asks the user to select the picture. And I always want the last picture taken. So I'm trying this way:

string imageFileName = Path.GetTempFileName(); // create temporary file for image

wiaItem = wiaRoot.TakePicture(); // take a picture

Cursor.Current = Cursors.WaitCursor; // could take some time

this.Refresh();

wiaItem.Transfer(imageFileName, false); // transfer picture to our temporary file

pictureBox1.Image = Image.FromFile(imageFileName); // create Image instance from file

Marshal.ReleaseComObject(wiaItem);

But the method TakePicture() returns null, and so I can't transfer the image. The strangest thing is that the picture was really taken after the method TakePicture() was called, since if I go to the webcam manually the picture is there! I just don't get it why it doesn't return a value.

To summarize, I either need one of this two: 1. Get TakePicture() to work, returning a value I can use. 2. Access the list of the webcam's pictures automatically, so I can retrieve the last picture taken.

Best regards and thanks for the help, Micael.

Answer

Philip Rieck picture Philip Rieck · Nov 30, 2010

From what I can see, wiaItem = wiaRoot.TakePicture() is going down the wrong path. Try this:

string imageFileName;
wiaRoot.TakePicture( out takenFileName);
pictureBox1.Image = Image.FromFile(imageFileName);

TakePicture saves a picture to a file, and returns the new file's name as an output parameter.

Edit per your comment - are you using the "windows 7 version" of WiaLib? If so, try something like this:

var manager = new DeviceManagerClass();
Item wiaItem;
Device device = null;
foreach (var info in manager.DeviceInfos)
{
    if (info.DeviceID == DESIRED_DEVICE_ID)
    {
        device = info.Connect();
        wiaItem = device.ExecuteCommand(CommandID.wiaCommandTakePicture);
    }
}

where you use the ExecuteCommand with the well known guid (also exposed from the COM interop wrapper) rather than TakePicture. It worked for my webcam, in any case.