Silverlight 4 Webcam Demo

22 02 2010

During my visit to Finland last month, I got the opportunity to demonstrate some of the new features in Silverlight 4 in demo-form. Today, I’ll review the webcam demo.

Silverlight 4 webcam demo


Silverlight 4 webcam demo

Application Layout

The layout of this application is fairly simple. In the image above, you see the entire UI of the app. It consists of a header, a big rectangle where the camera feed will be displayed (flag ATM), a button for activating the camera and a button for taking snapshots. Below the two buttons is a smaller rectangle which stores taken snapshots and below that, a print button (which I’ll leave out of this demo). With the help of a series of grids and rectangles; most of this is put together easily.

Silverlight 4 webcam demo

The one tricky area is this field which is supposed to keep thumbnails of snapshots taken with the camera. This is composed of a Border with a ListBox inside of it. The ListBox has two special properties set; ListBox.ItemTemplate and ListBox.ItemsPanel. The first looks like this:

<ListBox.ItemTemplate>
   <DataTemplate>
     <Image 
         Height="80" 
         Margin="5"
         Source="{Binding}"
         Stretch="UniformToFill" 
         VerticalAlignment="Center"  
      />
  </DataTemplate>
</ListBox.ItemTemplate>

This code tells us to fill up with only Image objects of a certain height which will be passed to us through code in a later stage.
The second custom property looks like this:

<ListBox.ItemsPanel>
   <ItemsPanelTemplate>
      <StackPanel
          Orientation="Horizontal"
          VerticalAlignment="Center"
          HorizontalAlignment="Center"
       />
   </ItemsPanelTemplate>
</ListBox.ItemsPanel>

This code tells us to present the items in the Listbox as a horizontal StackPanel. In this way we get a list of thumbnails that grows dynamically. The ListBox allows us to scroll and select multiple items; something the StackPanel alone is unable to offer. 

Initiating the camera

To breathe life into this cold, dead layout, we need some magical code. Please note that webcam functionality is only available in Silverlight4 and requires Visual Studio 2010.

First things first, I’ve added three objects available throughout the application;
CaptureSource captureSource;
ObservableCollection<WriteableBitmap> capturedImages;

Silverlight 4 webcam demo

The first button (“Start Cam”) will contain a click event which starts the webcam. The first step is to determine if there is a webcam present. To do this we write the following code:

// Determine if we have access to webcams
            if (!CaptureDeviceConfiguration.AllowedDeviceAccess)
            {
                // if not, request access
                if (!CaptureDeviceConfiguration.RequestDeviceAccess())
                {
                    // denied!
                    return;
                }
            }

Both these properties are included in System.Windows.Media. When we’re sure that a camera is present we’ll disable the Start button and set the listbox as an image receptor:

Start.IsEnabled = false;
capturedImages = new ObservableCollection<WriteableBitmap>();
Thumbnails.ItemsSource = capturedImages;

Now to actually start the camera, we instantiate our CaptureSource and assign the default video capture device as its video stream. If this succeeds, we want to start the camera up.  

//Set the default webcam as source
captureSource = new CaptureSource();
captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
            if (captureSource.VideoCaptureDevice != null)
            {
                VideoBrush PreviewBrush = new VideoBrush();
                PreviewBrush.SetSource(captureSource);
                Camera.Fill = PreviewBrush;
                Camera.Opacity = 1;

                //Start the cam!
                Snap.IsEnabled = true;
                captureSource.Start();
            }
            else
            {
                MessageBox.Show("No webcam detected!");
                Start.IsEnabled = true;
            }

Notice that the way we enable the camera feed is by making it into a Video Brush. Imagine that this video feed can be used anywhere you use brushes; text, buttons or even backgrounds. Not very functional, but very cool. “Snap” here refers to the second button.

Taking the picture

Once the capture source is initiated, we can start snapping images. I’ve created a click event for the second button (“Snap Shot”).

Silverlight 4 webcam demo

//Capture an image and add it to the collection
            captureSource.AsyncCaptureImage(
                (Img) =>
                {
                    capturedImages.Add(Img);
                }
            );

With this code, we easily capture an image and add it to our collection. As we do this, the picture is added to our ListBox as a thumbnail.

The next step

Right now, we have an application which takes snapshots of someone with a webcam. This can extend into a photo booth which prints small image strips (which mine did. Very cute), a photo manipulation service or why not a component that allows a user to save a profile image directly instead of uploading and cropping images?

Silverlight 4 webcam demo Silverlight 4 webcam demo


Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

Join 84 other followers