Rants and Raves

Thanks for visiting my blog!

Taking a WebCam Photo with Silverlight
Taking a WebCam Photo with Silverlight
November 23, 2009

Url: http://wilderminds.blob.core.windows.net/downloads/takingmypicture…

UPDATED: Fixed changes to API after Beta.  New Download too.

WebCam and Microphone support was one of the most requested features for Silverlight and Microsoft has answered the call. There are several ways to interact with the WebCam, but i’ll start with the most simple.  I’ve written a simple demo that you can download here that will let you start the WebCam, take a snapshot from the WebCam and save it out as an image:

The first class to be concerned with is the CaptureSource class. This class allows you to collect the video feed from the camera and use it with a VideoBrush to paint it on some surface. First let’s figure out how to actually enable the camera. To start the webcam, you must request permission. You can do this with the CaptureDeviceConfiguration class. You can call the class’ RequestDeviceAccess to ask the user to give you permission.  In addition, you can ask the class whether access has already been given by calling AllowedDeviceAccess property.  Surrounding the starting of the webcam is usually how thats handled like below:

CaptureSource src = new CaptureSource();

void cameraButton_Click(object sender, RoutedEventArgs e)
{
  if (CaptureDeviceConfiguration.AllowedDeviceAccess ||
    CaptureDeviceConfiguration.RequestDeviceAccess())
  {
    src.Start();
  }
}

By default, the CaptureSource uses the first found device, but you can also use the CaptureDeviceConfiguration class to iterate through the devices and attach the right one to the CaptureSource as well.

While you would normally use the VideoSink and AudioSink classes to actually capture actual samples, you can also use the CaptureSource class to capture individual frames of the webcam. A future example will delve into the sink classes, but in this example lets grab an individual frame. In fact, we can use the CaptureSource to make the webcam act like a camera.  The CaptureSource class has an CaptureImageAsync method (and CaputerImageCompleted event) that presents a callback to retrieve a WriteableBitmap of the capture source. In this example I am taking the bitmap and showing it on an image control:

src.CaptureImageCompleted  += (s,a) =>
  {
    snapshot.Source = a.Result;
    src.Stop();
  };

src.CaptureImageAsync();

You can download the sample here:

http://wilderminds.blob.core.windows.net/downloads/takingmypicture.zip