Capture Image From Webcam Video Using HTML5 Using JavaScript And Upload To Server Using C#

Today I am going to show you how to capture images from the webcam using JavaScript and HTML5 and upload on the server using a simple Ajax call using C#.
 
For your reference I have attached zip file of the MVC project with this article.
 
Below are the steps to perform this requirment. 
  1. Access Webcam by taking permission from user 
  2. Once you have the success permission from user, then capture the image on Canvas
  3. Make Ajax call to send Canvas Image to Server with the help of Base64 data
  4. And upload Base64 data as an image on the server folder
Here one question can arrise, as to why we use C# code to upload image, and why not JavaScript. So the answer is JavaScript does not have permission to access File System for security reasons.
 
So let's get started.  
 
HTML 
  1. <div class="jumbotron" style="margin-top:20px;padding:20px;">    
  2.     <p><span id="errorMsg"></span></p>    
  3.     <div class="row">    
  4.         <div class="col-lg-6">    
  5.             <!-- Here we streaming video from webcam -->    
  6.             <h4>    
  7.                 Video coming from Webcam  <button class="btn btn-primary" id="btnCapture">Capture to Canvas >></button>    
  8.             </h4>    
  9.             <video id="video" playsinline autoplay></video>    
  10.         </div>    
  11.     
  12.         <div class="col-lg-6">    
  13.             <h4>    
  14.                 Captured image from Webcam <input type="button" class="btn btn-primary" id="btnSave" name="btnSave" value="Save the canvas(image) to server" />    
  15.             </h4>    
  16.             <!-- Webcam video snapshot -->    
  17.             <canvas style="border:solid 1px #ddd;background-color:white;" id="canvas" width="475" height="475"></canvas>    
  18.         </div>    
  19.     </div>    
  20. </div>     
Scripts 
  1. <script type="text/javascript">  
  2.     var video = document.querySelector("#video");  
  3.   
  4.     // Basic settings for the video to get from Webcam  
  5.     const constraints = {  
  6.         audio: false,  
  7.         video: {  
  8.             width: 475, height: 475  
  9.         }  
  10.     };  
  11.   
  12.     // This condition will ask permission to user for Webcam access  
  13.     if (navigator.mediaDevices.getUserMedia) {  
  14.         navigator.mediaDevices.getUserMedia(constraints)  
  15.             .then(function (stream) {  
  16.                 video.srcObject = stream;  
  17.             })  
  18.             .catch(function (err0r) {  
  19.                 console.log("Something went wrong!");  
  20.             });  
  21.     }  
  22.   
  23.     function stop(e) {  
  24.         var stream = video.srcObject;  
  25.         var tracks = stream.getTracks();  
  26.   
  27.         for (var i = 0; i < tracks.length; i++) {  
  28.             var track = tracks[i];  
  29.             track.stop();  
  30.         }  
  31.         video.srcObject = null;  
  32.     }  
  33. </script>  
  34.   
  35. <script type="text/javascript">  
  36.     // Below code to capture image from Video tag (Webcam streaming)  
  37.     $("#btnCapture").click(function () {  
  38.         var canvas = document.getElementById('canvas');  
  39.         var context = canvas.getContext('2d');  
  40.   
  41.         // Capture the image into canvas from Webcam streaming Video element  
  42.         context.drawImage(video, 0, 0);  
  43.     });  
  44.   
  45.     // Upload image to server - ajax call - with the help of base64 data as a parameter  
  46.     $("#btnSave").click(function () {  
  47.   
  48.         // Below new canvas to generate flip/mirron image from existing canvas  
  49.         var destinationCanvas = document.createElement("canvas");  
  50.         var destCtx = destinationCanvas.getContext('2d');  
  51.   
  52.   
  53.         destinationCanvas.height = 500;  
  54.         destinationCanvas.width = 500;  
  55.   
  56.         destCtx.translate(video.videoWidth, 0);  
  57.         destCtx.scale(-1, 1);  
  58.         destCtx.drawImage(document.getElementById("canvas"), 0, 0);  
  59.   
  60.         // Get base64 data to send to server for upload  
  61.         var imagebase64data = destinationCanvas.toDataURL("image/png");  
  62.         imagebase64data = imagebase64data.replace('data:image/png;base64,''');  
  63.         $.ajax({  
  64.             type: 'POST',  
  65.             url: '/Home/UploadWebCamImage',  
  66.             data: '{ "imageData" : "' + imagebase64data + '" }',  
  67.             contentType: 'application/json; charset=utf-8',  
  68.             dataType: 'text',  
  69.             success: function (out) {  
  70.                 alert('Image uploaded successfully..');  
  71.             }  
  72.         });  
  73.     });  
  74. </script>  
Below is the condition which actually asks the user for the Webcam permission.
  1. if (navigator.mediaDevices.getUserMedia)  
CSS
 
Note
We need to add below CSS to flip the video and canvas as webcam is not showing mirror video.
  1. <style type="text/css">  
  2.     /* Flipping the video as it was not mirror view */  
  3.     video {  
  4.         -webkit-transform: scaleX(-1);  
  5.         transform: scaleX(-1);  
  6.         margin-top5px;  
  7.     }  
  8.   
  9.     /* Flipping the canvas image as it was not mirror view */  
  10.     #canvas {  
  11.         -moz-transform: scaleX(-1);  
  12.         -o-transform: scaleX(-1);  
  13.         -webkit-transform: scaleX(-1);  
  14.         transform: scaleX(-1);  
  15.         filter: FlipH;  
  16.         -ms-filter: "FlipH";  
  17.     }  
  18. </style>  
C# Code  
  1. public string UploadWebCamImage(string imageData)  
  2. {  
  3.             string filename = Server.MapPath("~/UploadWebcamImages/webcam_") + DateTime.Now.ToString().Replace("/""-").Replace(" ""_").Replace(":""") + ".png";  
  4.             using (FileStream fs = new FileStream(filename, FileMode.Create))  
  5.             {  
  6.                 using (BinaryWriter bw = new BinaryWriter(fs))  
  7.                 {  
  8.                     byte[] data = Convert.FromBase64String(imageData);  
  9.                     bw.Write(data);  
  10.                     bw.Close();  
  11.                 }  
  12.             }  
  13.             return "success";  
  14. }  
So once all the setup is done and we run the project, first we have to give permission s for the Webcam on the  browser on which the application is running as below.
 
Chrome
 
 
Firefox
 
 
Let's have a look at the running project
 
HTML after giving permission to access webcam,
 
 
HTML After clicking the capture button. 
 
 
HTML after clicking the save the image to Server,
 
 
And here we can see the uploaded image on the project folder. 
 
 
Please download the source coude attached with this Article and change it according to your requirement.
 
Notes
Due to the large size I have not added below packages in the zip foder as they were created by defauly the Visual Studio 2019. 
  • Microsoft.AspNet.Mvc.5.2.7
  • Microsoft.AspNet.Razor.3.2.7
  • Microsoft.AspNet.WebPages.3.2.7
  • Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0
  • Microsoft.Web.Infrastructure.1.0.0.0  
Happy Coding!!