Capturing Image From Web Cam in ASP.Net

This article provides the procedure for capturing an image from a webcam and store it in folder.

Here I used JSON, jQuery, SQL and C# to do it.

Preparation

  1. Download the webcam folder and extract it.
  2. Add that entire folder to your web application.
  3. Download the Scripts folder and run them in your SQL Server.
  4. Change the database name in your webconfig file.

Now we are ready to go.

Step 1: Starting with SQL.

The following is the table and Stored Procedure that I have used.

Table

Table

Stored Procedure
 
Stored Procedure

Show Records
 
Show Records

Step 2: Now we are starting the coding.
  • Create a new project
  • Select Template Visual C# in side select Web.
  • After Selecting Select ASP.NET Web Forms Application.
  • Enter Name for application.

Step 3: Creating the WebCamCapture.aspx page.

Add a web form to your application and name it WebCamCapture.aspx.

Add the following Styles and Controls the page.

Controls

  1. Image Control
  2. Linkbutton.
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head id="Head1" runat="server">  
  3.     <%--<meta http-equiv="refresh" content="30;url=WebCamCapture.aspx">--%>  
  4.     <style type="text/css">  
  5.         #profile_pic_wrapper  
  6.         {  
  7.             position: relative;  
  8.             border: #ccc solid 1px;  
  9.             width: 120px;  
  10.             height: 120px;  
  11.             border: none;  
  12.         }  
  13.         #profile_pic_wrapper a  
  14.         {  
  15.             position: absolute;  
  16.             display: none;  
  17.             top: 30;  
  18.             right: 0;  
  19.             margin-top: -30px;  
  20.             line-height: 20px;  
  21.             padding: 5px;  
  22.             color: #fff;  
  23.             background-color: #333;  
  24.             width: 110px;  
  25.             text-decoration: underline;  
  26.             text-align: center;  
  27.             z-index: 100;  
  28.             text-decoration: none;  
  29.             font-family: Arial;  
  30.             font-size: 10px;  
  31.         }  
  32.         #profile_pic_wrapper:hover a  
  33.         {  
  34.             position: absolute;  
  35.             margin: 90px 0px 0px 0px;  
  36.             display: block;  
  37.             text-decoration: none;  
  38.             font-family: Arial;  
  39.             font-size: 10px;  
  40.         }  
  41.         #profile_pic_wrapper:hover a:hover  
  42.         {  
  43.             text-decoration: none;  
  44.             font-family: Arial;  
  45.             font-size: 10px;  
  46.         }  
  47.         .profile_pic  
  48.         {  
  49.             width: 120px;  
  50.             height: 120px;  
  51.         }  
  52.     </style>  
  53.     <title>Web capture</title>  
  54. </head>  
  55. <body>  
  56.     <form id="form1" runat="server">  
  57.       <div style="float: left; padding-left: 35px;" id="profile_pic_wrapper">  
  58.       <asp:Image ID="img" Width="120" Height="120" runat="server" Style="float: left;" />  
  59.       <asp:LinkButton ID="Linkbutton1" runat="server" OnClick="Linkbutton1_Click">Change  Photo</asp:LinkButton>  
  60.         </div>  
  61.     </form>   
  62. </body>  
  63. </html>
Here is snapshot of the page.
 
Page 

Step 4: After adding the Styles and Controls to your page.

On the load of this page we will set the image to an image control from the database.

The following is the on load code.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.    if (!IsPostBack)  
  4.    {  
  5.        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());  
  6.        // connection of sql   
  7.       // used this StoredProcedure for reteriving image  
  8.       // According to user id i am reteriving image from database  
  9.       SqlCommand cmd = new SqlCommand("Usp_InsertImageDT", con);  
  10.       cmd.CommandType = CommandType.StoredProcedure;  
  11.       cmd.Parameters.AddWithValue("@UserImagename"null);  
  12.       cmd.Parameters.AddWithValue("@UserImagePath"null);  
  13.       cmd.Parameters.AddWithValue("@UserID", 0);  
  14.       cmd.Parameters.AddWithValue("@QueryID", 2);                 
  15.       DataSet ds = new DataSet();  
  16.       SqlDataAdapter da = new SqlDataAdapter();  
  17.       da.SelectCommand = cmd;  
  18.       da.Fill(ds);  
  19.        if (ds.Tables[0].Rows.Count > 0)  
  20.        {  
  21.            img.ImageUrl = ds.Tables[0].Rows[0]["UserImagePath"].ToString();  
  22.            // Assiging image to Image Control  
  23.        }  
  24.    }  
  25. } 

Step 5: Button Linkbutton1 click code.

  1. protected void Linkbutton1_Click(object sender, EventArgs e)  
  2. {  
  3.     // to how Pop and calling another Page in Popup.  
  4.     string url = "/WebCam/Captureimage.aspx";  
  5.     string s = "window.open('" + url + "', 'popup_window', 'width=900,height=460,left=100,top=100,resizable=no');";  
  6.     ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);  
  7. }  

 

Step 6:

Add a folder Name (WebCam) to your project that I am providing for you.

You can download it from the top folder.

Here is snapshot of the folder.

It contains all files the required for web cam image capturing.

Just add it.

Project

In this folder are the following 2 .Aspx pages.
  1.  Captureimage.aspx

    The Captureimage.aspx Page contains code for waking up the WebCam and capturing the image.
     
  2. Baseimg.aspx

    After capturing an image it will call the baseimg.aspx page and provide a base64 string to it.

    On the load of this page it receive the base64 string.

    Using a FileStream and Binary Writer it will draw an image.

    After drawing it will save it to a folder and insert it into the database.

Step 7:

Captureimage.aspx Page

It contains 2 main JS Files.

  1. <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>  
  2. <script src="Scripts/jquery.webcam.js" type="text/javascript"></script>   

 

And JavaScript Code.

Snapshot of Captureimage.aspx

Snapshot of Captureimage

This will pop-up when you will click on the change Photo link button on the image.

It will ask for the Adobe Flash player setting.

Just click "Allow".

After clicking on Allow:
 
Clicking

After clicking of Capture.
 
Capture

When you click on the "Submit" Button then it will call the page Baseimg.aspx for writing the Base 64 string .

The following is the JSON script for calling baseimg.aspx and reloading the image on the parent page.

  1. <div style="text-align: center; margin-bottom: 46px;">  
  2.         <a href="#" id="filter" onclick="javascript:UploadPic();">  
  3.         <input type="image" id="Submit" runat="server" src="images/submitBTN.png" />  
  4.        </a>  
  5. </div>  
  6. function UploadPic() {  
  7.     debugger;  
  8.     // generate the image data  
  9.    var canvas = document.getElementById("canvas");  
  10.    var dataURL = canvas.toDataURL("image/png");  
  11.     // Sending the image data to Server  
  12.      $.ajax({  
  13.           type: 'POST',  
  14.           url: "baseimg.aspx",  
  15.           data: { imgBase64: dataURL },  
  16.           success: function () {  
  17.           alert("Done, Picture Uploaded.");  
  18.             window.opener.location.reload(true); // reloading Parent page  
  19.             window.close();  
  20.             window.opener.setVal(1);  
  21.             return false;  
  22.          }  
  23.     });  
  24. }

 

Step 8:

Baseimg.aspx

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     //called page form json for creating imgBase64 in image  
  4.     StreamReader reader = new StreamReader(Request.InputStream);  
  5.     String Data = Server.UrlDecode(reader.ReadToEnd());  
  6.     reader.Close();  
  7.     DateTime nm = DateTime.Now;  
  8.     string date = nm.ToString("yyyymmddMMss");  
  9.     //used date for creating Unique image name  
  10.     Session["capturedImageURL"] = Server.MapPath("~/Userimages/") + date + ".jpeg";   
  11.     Session["Imagename"] = date + ".jpeg";  
  12.     // We can use name of image where ever we required that why we are storing in Session  
  13.     drawimg(Data.Replace("imgBase64=data:image/png;base64,", String.Empty), Session["capturedImageURL"].ToString());  
  14.     // it is method  
  15.     // passing base64 string and string filename to Draw Image.  
  16.     insertImagePath(Session["Imagename"].ToString(), "~/Userimages/" + Session["Imagename"].ToString());  
  17.     // it is method  
  18.     //inserting image in to database  
  19. }

Drawing Method

  1. public void drawimg(string base64, string filename)  // Drawing image from Base64 string.  
  2. {  
  3.     using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))  
  4.     {  
  5.         using (BinaryWriter bw = new BinaryWriter(fs))  
  6.         {  
  7.             byte[] data = Convert.FromBase64String(base64);  
  8.             bw.Write(data);  
  9.             bw.Close();  
  10.         }  
  11.     }  
  12. }

 

Insert Image to Database Method

  1. public void insertImagePath(string imagename, string imagepath) // use for inserting image when it is created.  
  2. {  
  3.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());  
  4.     SqlCommand cmd = new SqlCommand("Usp_InsertImageDT", con);  
  5.     cmd.CommandType = CommandType.StoredProcedure;  
  6.     cmd.Parameters.AddWithValue("@UserImagename", imagename);  
  7.     cmd.Parameters.AddWithValue("@UserImagePath", imagepath);  
  8.     cmd.Parameters.AddWithValue("@UserID", 1);  
  9.     cmd.Parameters.AddWithValue("@QueryID", 1);  
  10.     con.Open();  
  11.     cmd.ExecuteNonQuery();  
  12.     con.Close();  
  13. }

 

Step 9

Final output.

output
 
Final output
 
Result

I am providing you the entire solution and table script. If you have any problem creating this then just run this solution and check it else you can comment on this article.