Capture image from web camra

Life is 10% what happens to us and 90% how we react to it. If you don't build your dream, someone else will hire you to help them build theirs.

Capture image from web camra

In order to capture images from Web Camera (Webcam) I am making use of jQuery Webcam plugin. The images captured using Web Camera (Webcam) will be saved in folder and displayed in ASP.Net Image control.

jQuery Webcam Plugin

You will need to download the jQuery Webcam plugin from the following location, it is also available in the attached source code of this article.

Download jQuery Webcam Plugin

HTML Markup

The HTML Markup consist of an HTML DIV for the Web Camera, an Image control for displaying the captured image, an HTML SPAN for displaying the status of the Web Camera and a Button for capturing the picture using the Web Camera.

<form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td align="center">
            <u>Live Camera</u>
        </td>
        <td>
        </td>
        <td align="center">
            <u>Captured Picture</u>
        </td>
    </tr>
    <tr>
        <td>
            <div id="webcam">
            </div>
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            <asp:Image ID="imgCapture" runat="server" Style="visibility: hidden; width: 320px;
                height: 240px" />
        </td>
    </tr>
</table>
<br />
<asp:Button ID="btnCapture" Text="Capture" runat="server" OnClientClick="return Capture();" />
<br />
<span id="camStatus"></span>
</form>
Namespaces
using System.IO;
using System.Web.Services;
Server Side Implementation

The captured image is send as raw data in the form of Hexadecimal string by the jQuery Webcam Flash to the server and hence it has to be captured in the Page Load event of the ASP.Net page.
If the Request.InputStream has data then it is read using StreamReader and then converted to a Hexadecimal string and then the Hexadecimal string is converted to array of bytes which is then saved as an image file.
The path of the image is also saved as URL in a Session variable as it will be used later when the AJAX call is made to the GetCapturedImage WebMethod to get the URL of the saved image.


protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        if (Request.InputStream.Length > 0)
        {
            using (StreamReader reader = new StreamReader(Request.InputStream))
            {
                string hexString = Server.UrlEncode(reader.ReadToEnd());
                string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
                string imagePath = string.Format("~/Captures/{0}.png", imageName);
                File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(hexString));
                Session["CapturedImage"] = ResolveUrl(imagePath);
            }
        }
    }
}
 
private static byte[] ConvertHexToBytes(string hex)
{
    byte[] bytes = new byte[hex.Length / 2];
    for (int i = 0; i < hex.Length; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    }
    return bytes;
}
 
[WebMethod(EnableSession = true)]
public static string GetCapturedImage()
{
    string url = HttpContext.Current.Session["CapturedImage"].ToString();
    HttpContext.Current.Session["CapturedImage"] = null;
    return url;
}
Integrating the jQuery Webcam Plugin in ASP.Net

Inside the jQuery load event handler, I have applied the jQuery Webcam plugin to the HTML DIV so that the live web camera recording can be played on the web page.

The following are the configuration properties of the jQuery Webcam plugin.

1. width – Width of the DIV that displays the live camera.

2. height – Height of the DIV that displays the live camera.

3. mode – There are different modes such as callback, save, etc. I am using save mode as I need to save the captured image to the server.

4. swffile – The path of the Flash file that will be used for displaying the web camera on the page.

In addition to the above configuration properties the following events have been used.

1. debug – This event is a debugging event and is triggered after every time the jQuery Webcam plugin performs some operation. This event can be used to display the status of the jQuery Webcam plugin.

2. onSave – This event is triggered after the image is captured and uploaded to the server.

3. onCapture - This event is trigged when the capture function of the jQuery Webcam plugin is executed.

When the ASP.Net Button is clicked the JavaScript function named Capture is executed which makes a call to the jQuery Webcam plugin capture method.

Once the image is captured it is uploaded to the server using the jQuery Webcam plugin’s save method which is called within the OnCapture event handler.
Finally the OnCapture event handler makes a jQuery AJAX call to the GetCapturedImage method which gets the URL of the captured image from the server and the URL is then assigned to the ASP.Net Image control.

Note: This plugin makes use of Adobe Flash plugin and has a requirement that Adobe Flash plugin has to be installed in the browser to make it work.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='<%=ResolveUrl("~/Webcam_Plugin/jquery.webcam.js") %>' type="text/javascript"></script>
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/Default.aspx") %>';
$(function () {
    jQuery("#webcam").webcam({
        width: 320,
        height: 240,
        mode: "save",
        swffile: '<%=ResolveUrl("~/Webcam_Plugin/jscam.swf") %>',
        debug: function (type, status) {
            $('#camStatus').append(type + ": " + status + '<br /><br />');
        },
        onSave: function (data) {
            $.ajax({
                type: "POST",
                url: pageUrl + "/GetCapturedImage",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    $("[id*=imgCapture]").css("visibility", "visible");
                    $("[id*=imgCapture]").attr("src", r.d);
                },
                failure: function (response) {
                    alert(response.d);
                }
            });
        },
        onCapture: function () {
            webcam.save(pageUrl);
        }
    });
});
 function Capture() {
    webcam.capture();
    return false;
}
</script>