How to Capture Image using web camera in Asp.net and C#.NET / VB.NET

Hello Guys, In this blog post we are going to learn how to capture an image using web camera in .NET Web Application using Asp.net and C#.NET / VB.NET 




In order to capture image using Web Camera (webcam) we are going to use Webcam.js Javascript library. 

Install the webcam.js file from below location and copy to your javascript folder inside your application. 


Copy below code in your ASPX view page

<div class="container">
                <div class="row">
                    <div class="col-md-6 col-xl">
                        <label>Capture Image</label>
                    </div>
                    <div class="col-md-6 col-xl">
                        <label>Upload Image</label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 col-xl">
                        <div id="webcam"></div>
                    </div>
                    <div class="col-md-6 col-xl">
                        <img id="imgCapture" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 col-xl">
                        <input type="button" class="btn-primary btn btn-block" id="btnCapture" value="Capture" />
                    </div>
                    <div class="col-md-6 col-xl">
                       <input type="button" class="btn-primary btn btn-block" id="btnUpload" value="Upload" />
                    </div>
                </div>
            </div>
In the above markup we can see the html element added for displaying live web camera and img control displaying captured image one HTML button for capturing the live web camera image and another button for uploading the captured image to a folder in the application.
Following are the namespaces required in the code behind file
 
using System.IO;
using System.Web.Services;

Add the following lines of code in code behind file

[WebMethod()]
    public static bool SaveCapturedImage(string imageData)
    {
        string fileName = DateTime.Now.ToString("dd/mmm/yyyy hh:mm tt");

        if (imageData != string.Empty)
        {
            //Convert Base64 Encoded string to Byte Array.
            byte[] imageBytes = Convert.FromBase64String(imageData.Split(',')[1]);

            //Save the Byte Array as Image File.
            string filePath = HttpContext.Current.Server.MapPath(string.Format("~/CapturedImages/{0}.jpg", fileName));
            File.WriteAllBytes(filePath, imageBytes);
            return true;
        }
        else
            return false;
    }

The above service method will converts the base64 encoded string which is passed to the service method from jquery AJAX call to byte array then saves the byte array as image file in the specified location.

Add the jquery and webcam.js reference to the aspx view page

 <script src="js/jquery/jquery.js" type="text/javascript"></script>
    <script src="js/WebCam.js" type="text/javascript"></script>



The following code will apply the webcam.js to HTML DIV element inside jquery document ready event handler


Webcam.set({
                width: 620,
                height: 500,
                image_format: 'jpeg',
                jpeg_quality: 100
            });
            Webcam.attach('#webcam');



1) Width: this property will set the width of DIV element which shows the live web camera 

2) Height: this property will set the height of DIV element which shows the live web camera 

3) Image_format: this property will set the file format for the captured image 

4) Jpeg_quality: this property will set the image quality

When we click on the Capture button then the below code will capture the image from the live web cam using the snap function of the jquery webcam.js then the captured image data which is in Base64 format assigned to the img html element.

$("#btnCapture").click(function () {
                Webcam.snap(function (data_uri) {
                    $("#imgCapture")[0].src = data_uri;
                    $("#btnUpload").removeAttr("disabled");
                });
            });
            



When we click on the Upload button then the Base64 image data is uploaded to the server using jquery AJAX call


$("#btnUpload").click(function () {
                $.ajax({
                    type: "POST",
                    url: "CaptureImageCS.aspx/SaveCapturedImage",
                    data: "{data: '" + $("#imgCapture")[0].src +  "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        if (r == true) {
                            alert('Image Uploaded Successfully');
                        }
                        else alert('Failed to upload image, Please try again');
                    }
                });
            });

Complete code in ASP.NET and C#.NET
<body>
    <table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <th align="center"><u>Live Camera</u></th>
        <th align="center"><u>Captured Picture</u></th>
    </tr>
    <tr>
        <td><div id="webcam"></div></td>
        <td><img id = "imgCapture" /></td>
    </tr>
    <tr>
        <td align = "center">
            <input type="button" id="btnCapture" value="Capture" />
        </td>
        <td align = "center">
            <input type="button" id="btnUpload" value="Upload" disabled = "disabled" />
        </td>
    </tr>
    </table>
    <script src="js/jquery/jquery.js" type="text/javascript"></script>
    <script src="js/WebCam.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            Webcam.set({
                width: 620,
                height: 500,
                image_format: 'jpeg',
                jpeg_quality: 90
            });
            Webcam.attach('#webcam');
            $("#btnCapture").click(function () {
                Webcam.snap(function (data_uri) {
                    $("#imgCapture")[0].src = data_uri;
                    $("#btnUpload").removeAttr("disabled");
                });
            });
            $("#btnUpload").click(function () {
                $.ajax({
                    type: "POST",
                    url: "CaptureImageCS.aspx/SaveCapturedImage",
                    data: "{data: '" + $("#imgCapture")[0].src +  "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        if (r == true) {
                            alert('Image Uploaded Successfully');
                        }
                        else alert('Failed to upload image, Please try again');
                    }
                });
            });
        });
    </script>
</body>



Code Behind



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;

public partial class CaptureImageCS : System.Web.UI.Page
{
    [WebMethod()]
    public static bool SaveCapturedImage(string imageData)
    {
        string fileName = DateTime.Now.ToString("dd/mmm/yyyy hh:mm tt");

        if (imageData != string.Empty)
        {
            //Convert Base64 Encoded string to Byte Array.
            byte[] imageBytes = Convert.FromBase64String(imageData.Split(',')[1]);

            //Save the Byte Array as Image File.
            string filePath = HttpContext.Current.Server.MapPath(string.Format("~/CapturedImages/{0}.jpg", fileName));
            File.WriteAllBytes(filePath, imageBytes);
            return true;
        }
        else
            return false;
    }
}

Complete code in ASP.NET and VB.NET 

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="CaptureImage.aspx.vb" Inherits="CaptureImageUsingWebCam.CaptureImage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Capture Image</title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
            <div class="container">
                <div class="row">
                    <div class="col-md-6 col-xl">
                        <label>Capture Image</label>
                    </div>
                    <div class="col-md-6 col-xl">
                        <label>Upload Image</label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 col-xl">
                        <div id="webcam"></div>
                    </div>
                    <div class="col-md-6 col-xl">
                        <img id="imgCapture" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 col-xl">
                        <input type="button" class="btn-primary btn btn-block" id="btnCapture" value="Capture" />
                    </div>
                    <div class="col-md-6 col-xl">
                       <input type="button" class="btn-primary btn btn-block" id="btnUpload" value="Upload" disabled="disabled" />
                    </div>
                </div>
            </div>

    </form>
</body>
<script src="js/jquery/jquery.js"></script>
<script src="js/WebCam.js"></script>
    <script type="text/javascript">
    $(function () {
        Webcam.set({
            width: 540,
            height: 440,
            image_format: 'jpeg',
            jpeg_quality: 90
        });
        Webcam.attach('#webcam');
        $("#btnCapture").click(function () {
            Webcam.snap(function (data_uri) {
                $("#imgCapture")[0].src = data_uri;
                $("#btnUpload").removeAttr("disabled");
            });
        });
        $("#btnUpload").click(function () {
            $.ajax({
                type: "POST",
                url: "CaptureImage.aspx/SaveCapturedImage",
                data: "{data: '" + $("#imgCapture")[0].src + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) { }
            });
        });
    });
    </script>
</html>
 

Code behind (VB)


Imports System.IO
Imports System.Web.Services

Public Class CaptureImage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    [WebMethod()]
    Public Shared Function SaveCapturedImage(ByVal data As String) As Boolean
        Dim fileName As String = DateTime.Now.ToString("dd/mmm/yyyy hh:mm tt")
        Dim imageBytes() As Byte = Convert.FromBase64String(data.Split(",")(1))
        Dim filePath As String = HttpContext.Current.Server.MapPath(String.Format("~/CapturedImages/{0}.jpg", fileName))
        File.WriteAllBytes(filePath, imageBytes)
        Return True
    End Function

End Class

Comments

Popular posts from this blog

Download Excel File using AJAX in JavaScript

How to Install GIT ?