dcsimg
 

Capturing an Image from a Webcam Using .NET

Thursday Nov 29th 2018 by Tapas Pal

Explore capturing a simple image and display in a Web page. The "jQuery-webcam" JavaScript library is used.

Introduction

Webcams are an easy and cost-effective way to take images from a video stream. In this modern era of smartphones, everyone has a camera which could be used by Web applications to capture live pictures. It's a widely used feature in the business world. In this article, I'm going to show you how to capture a simple image and display in a Web page. We are going to use the "jQuery-webcam" JavaScript library for capturing image from a Webcam. You also can store it in a folder and database.

Sample ASP.NET Application to Capture a Webcam Image

To start with, I have Created a .NET Web application using Framework version 4.5 and named it 'MyWebCamImage', as shown in Figure 1.

New .NET Web Application
Figure 1: New .NET Web Application

After naming it, just click the OK button. A new dialog will open; it will ask you to select a template. I have selected Empty template and clicked the OK button (see Figure 2).

New .NET Web Application Empty Template
Figure 2: New .NET Web Application Empty Template

After creating the Web application, we have to download and add webcam.js and related files to the project. To download the (webcam.js related) files, just visit the URL : https://github.com/infusion/jQuery-webcam, as shown in Figure 3. You can download this as a zip file.

JQuery Webcam Plug-in
Figure 3: jQuery Webcam Plug-in

Now, unzip the files. Figure 4 shows the complete view of the files that are in the zip folder.

List of Unzip files
Figure 4: List of Unzip files

Next, I have added the extracted files to the 'JavaScript_Webcam_Plugin' folder of the project. View Figure 5.

List of JavaScript files added in the Solution
Figure 5: List of JavaScript files added in the Solution

Next, I have created the View. It consists of an HTML DIV to display the Live Web Camera, an HTML Image element to display the captured image, an HTML SPAN to display the status of the Web Camera, and an HTML Button to capture the picture using the Web Camera.

Inside the jQuery load event handler, the jQuery Webcam plug-in is applied to the HTML DIV so that the live Web Camera recording can be played on the View.

When the Button is clicked, the JavaScript function named Capture is executed. This makes a call to the capture method of the jQuery Webcam plug-in.

the following CaptureCam.aspx code is written for capturing live image from the Webcam.

<%@ Page Language="C#" AutoEventWireup="true"
   CodeBehind="CaptureCam.aspx.cs"
   Inherits="MyWebCamImage.CaptureCam" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Capture Image from Cam</title>
<script type="text/javascript"
   src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3
   /jquery.min.js"></script>
<script src='<%=ResolveUrl("~/JavaScript_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("~/JavaScript_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*=MyimgCapture]").css("visibility",
                  "visible");
               $("[id*=MyimgCapture]").attr("src", r.d);
            },
            failure: function (response) {
               alert(response.d);
            }
         });
      },
      onCapture: function () {
         webcam.save(pageUrl);
      }
   });
});
function Capture() {
   webcam.capture();
   return false;
}
</script>
</head>
<body>
   <form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
   <tr>
      <td align="center">
         <u>My Live Camera</u>
      </td>
      <td>
      </td>
      <td align="center">
         <u>My Captured Picture</u>
      </td>
   </tr>
   <tr>
      <td>
         <div id="webcam">
         </div>
      </td>
      <td>
          
      </td>
      <td>
         <asp:Image ID="MyimgCapture" 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>
</body>
</html>

The previously captured image is sent as raw binary data in the form of a Hexadecimal string by the jQuery Webcam Flash to the server. Binary data is captured in the CaptureCam.aspx.cs code behind the Page Load event of the ASP.NET page.

Add validation. If the Request.InputStream has data, it is read by 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 because it will be used later when the AJAX call is made to the MyGetCapturedImage WebMethod to get the saved image's URL. Study the following server side C# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;

namespace MyWebCamImage
{
   public partial class CaptureCam : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!this.IsPostBack)
         {
            if (Request.InputStream.Length > 0)
            {
               using (StreamReader myreader = new
                  StreamReader(Request.InputStream))
               {
                  string myhexString = Server.UrlEncode
                     (myreader.ReadToEnd());
                  string myimageName = DateTime.Now.ToString
                     ("dd-MM-yy hh-mm-ss");
                  string myimagePath = string.Format
                     ("~/Captures/{0}.png", myimageName);
                  File.WriteAllBytes(Server.MapPath(myimagePath),
                     ConvertHexToBytes(myhexString));
                  Session["MyCapturedImage"] =
                     ResolveUrl(myimagePath);
               }
            }
         }
      }


      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 GetMyCapturedImage()
      {
         string Imageurl = HttpContext.Current.Session
            ["MyCapturedImage"].ToString();
         HttpContext.Current.Session["MyCapturedImage"] = null;
         return Imageurl;
      }
   }
}

Finally, execute the project and capture a live Webcam image.

Conclusion

I hope this article has explained how to capturing an image from a Webcam in an ASP.NET Web application.

That's all for today. Happy coding!

Home
Mobile Site | Full Site