Click here to Skip to main content
15,893,381 members
Articles / Programming Languages / C# 4.0

Capture Image from Webcam using Silverlight

Rate me:
Please Sign up or sign in to vote.
4.19/5 (9 votes)
8 Nov 2012CPOL5 min read 56.5K   4.6K   17  
Capture a frame from live webcam feed and save it as an image file to disk
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication1
{
    public class Imager
    {
        public static ImageTools.ExtendedImage ToImg(WriteableBitmap bitmap)
        {
            ImageTools.ExtendedImage image = new ImageTools.ExtendedImage(bitmap.PixelWidth, bitmap.PixelHeight);

            try
            {
                byte[] pixels = image.Pixels;
                int[] raster = bitmap.Pixels;
                if (raster != null)
                {
                    for (int y = 0; y < image.PixelHeight; y++)
                    {
                        for (int x = 0; x < image.PixelWidth; x++)
                        {
                            int pixelIndex = bitmap.PixelWidth * y + x;
                            int pixel = raster[pixelIndex];
                            byte a = (byte)(pixel >> 24 & 255);
                            float aFactor = (float)a / 255f;
                            if (aFactor > 0f)
                            {
                                byte r = (byte)((float)(pixel >> 16 & 255) / aFactor);
                                byte g = (byte)((float)(pixel >> 8 & 255) / aFactor);
                                byte b = (byte)((float)(pixel & 255) / aFactor);
                                pixels[pixelIndex * 4] = r;
                                pixels[pixelIndex * 4 + 1] = g;
                                pixels[pixelIndex * 4 + 2] = b;
                                pixels[pixelIndex * 4 + 3] = a;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException("Bitmap cannot accessed", e);
            }
            return image;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer (Senior)
United Kingdom United Kingdom
A software developer in pursuit of craftsmanship and the zen of software.

Comments and Discussions