Capturing Image from webcam in ASP.Net MVC

Introduction

This article shows how to capture an image using a webcam in MVC4 and in this application we will use a jQuery webcam.js plug-in for capturing images. I have seen that most online applications currently require webcam image capturing functionality in some way or another. Most social networking sites use this kind of functionality in their application for capturing user profile pictures.

Similarly I have written this article on how to capture a picture using webcam.js in ASP.Net web forms.

Here is the URL: C-SharpCorner

Agenda

  1. Create basic MVC application.
  2. Download and Adding webcam.js related reference files to project.
  3. Adding Controller ( PhotoController ).
  4. Adding Index view.
  5. Adding Action Method Capture( ).
  6. Adding Script for capturing Image.
  7. Adding Action Method and Script for binding image.
  8. Adding [HttpPost] Index Action Method.
  9. Displaying the index View in New Window.
  10. Changephoto.cshtml Code Snippet.
  11. PhotoController Code Snippet.
  12. Index.cshtml Code Snippet.
  13. Finally Output.

Create basic MVC application

Create a MVC 4 application and name it WebcamMVC.



After naming it just click on the OK button. A new dialog will then popup for selecting a template. Select Basic template and click the OK button.



After creating the application it's time to download and add webcam.js and related files to the project.

Downloading and adding webcam.js related reference files to project

For downloading (webcam.js related) files just visit the give URL: jQuery-webcam.

Here you can download the Zip file.



And the following is the complete view of the files that are In the Zip folder.



After downloading just extract the files and add all the files to the script folder of your project.



After adding the files, let's move to adding a Controller.

Adding Controller (PhotoController)

We will add a Controller with the name PhotoController.

Code Snippet of photocontroller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.IO;  
  7. namespace WebcamMVC.Controllers  
  8. {  
  9.     public class PhotoController : Controller  
  10.     {  
  11.         [HttpGet]  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.     }  
  17. }  
After adding a photo controller It created a default Index action method.

Now let's add a View to this Index action method.

Adding Index view

To add the View just right-click inside View and select Add View. A new dialog will popup for configuring the View. Don't change the name of the View, let it be “ Index”. Just click on the Add button.

After adding the View let's add some controls and scripts to it for capturing it and submitting it to the Controller.

Code Snippet of Index View
  1. <div style="margin: 0 auto; width: 980px; text-align: center">  
  2.         <div style="float: left; border: 4px solid #ccc; padding: 5px">  
  3.             <div id="Camera">  
  4.             </div>  
  5.             <br>  
  6.             <input type="button" value="Capture" />  
  7.         </div>  
  8.         <div style="float: left; margin-left: 20px; border: 4px solid #ccc; padding: 5px">  
  9.             <img id="show" style="width: 320px; height: 240px;" src="../../WebImages/person.jpg" />  
  10.             <br>  
  11.             <br>  
  12.             <input id="Submit1" type="submit" value="submit" />  
  13.         </div>  
  14. </div>   
After adding the controls now let's add scripts to it for capturing a picture.
 
This script is for displaying the webcam and has a method to capture images.
  1. @section scripts  
  2. {  
  3.         <script src="@Url.Content("~/Scripts/jquery.webcam.js")">  
  4.         </script>  
  5.         <script type="text/javascript">  
  6.             $("#Camera").webcam({  
  7.                 width: 320,  
  8.                 height: 240,  
  9.                 mode: "save",  
  10.                 swffile: "@Url.Content("~/Scripts/jscam.swf")",  
  11.                 onTick: function () { },  
  12.                 onSave: function () {  
  13.                     UploadPic();  
  14.                 },  
  15.                 onCapture: function () {  
  16.                     webcam.save("@Url.Content("~/Photo/Capture")/");  
  17.              },  
  18.                 debug: function () { },  
  19.                 onLoad: function () { }  
  20.   
  21.             });  
  22.   
  23.         </script>  
  24. }  
Now run this application and confirm that your Index View looks like this.



Adding Action Method Capture( )

For capturing an image I will add 1 new Action Method with the name Capture and another method to write stringtoBytes with the name String_To_Bytes2 in the same Photo controller.

Code Snippet of PhotoController
  1. public ActionResult Capture()    
  2. {    
  3.     var stream = Request.InputStream;    
  4.     string dump;    
  5.     using (var reader = new StreamReader(stream))    
  6.     {    
  7.         dump = reader.ReadToEnd();  
  8.         DateTime nm = DateTime.Now;    
  9.         string date = nm.ToString("yyyymmddMMss");    
  10.         var path = Server.MapPath("~/WebImages/" + date + "test.jpg");  
  11.         System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));  
  12.         ViewData["path"] = date + "test.jpg";  
  13.         Session["val"] = date + "test.jpg";    
  14.      }  
  15.       return View("Index");    
  16. }  
The Capture method contains code for getting a stream of the captured image. We will then call another method for writing the string to bytes String_To_Bytes2 and then save it to the WebImages folder in the project.

In the Capture method you can also see I have stored an image name in the session such that it can be retrieved anywhere in the application. 
  1. private byte[] String_To_Bytes2(string strInput)    
  2. {    
  3.     int numBytes = (strInput.Length) / 2;    
  4.     byte[] bytes = new byte[numBytes];    
  5.     for (int x = 0; x < numBytes; ++x)    
  6.     {    
  7.         bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);    
  8.     }    
  9.     return bytes;    
  10. }  
Adding Script for capturing Image

This Script will capture an image.
  1. @section scripts    
  2. {    
  3.         <script src="@Url.Content("~/Scripts/jquery.webcam.js")">    
  4.         </script>    
  5.         <script type="text/javascript">    
  6.             $("#Camera").webcam({    
  7.                 width: 320,    
  8.                 height: 240,    
  9.                 mode: "save",    
  10.                 swffile: "@Url.Content("~/Scripts/jscam.swf")",    
  11.                 onTick: function () { },    
  12.                 onSave: function () {    
  13.                     UploadPic();    
  14.                 },    
  15.                 onCapture: function () {    
  16.                     webcam.save("@Url.Content("~/Photo/Capture")/");    
  17.              },    
  18.                 debug: function () { },    
  19.                 onLoad: function () { }    
  20.             });    
  21.         </script>    
  22. }    
  23. onCapture: function () {    
  24.     webcam.save("@Url.Content("~/Photo/Capture")/");    
  25. }, 
Now we can see that the onCapture function contains the webcam.save(); function and the URL of the Action Method that we created in the Photo Controller.

To capture an Image on button click we need to call the function webcam.capture();
  1. <input type="button" value="Capture" onclick="webcam.capture();" />  


After writing the code for capturing let's move to binding the image that we have captured.

Adding Action Method and Script for binding image

For binding the image I wrote a JSON method with the name Rebind that will be called when I click on the Capture button.
  1. public JsonResult Rebind()  
  2. {  
  3.     string path = "http://localhost:55694/WebImages/" + Session["val"].ToString();  
  4.     return Json(path, JsonRequestBehavior.AllowGet);  
  5. }  
This method returns the path of the image that we captured.

This Uploadpic ajax function calls the JSON method Rebind() that returns the path of the image. We will bind this path to the image control.
  1. function UploadPic() {  
  2.         $.ajax({  
  3.             type: 'POST',  
  4.             url: ("@Url.Content("~/Photo/Rebind")/"),  
  5.             dataType: 'json',  
  6.             success: function (data) {  
  7.                 $("#show").attr("src", data);  
  8.                 document.getElementById('Submit1').disabled = false;  
  9.                 alert("Photo Capture successfully!");  
  10.             }  
  11.         });  
  12. }  
Similarly we are calling the UploadPic() function in the webcam script.
  1. onSave: function ()  
  2. {  
  3. UploadPic();  
  4. },  
Adding [HttpPost] Index Action Method

We need to submit a value for storing an image name. For this we will write a [HttpPost] method with a Name Index that will take Imagename as input. In this Action method you can write code for saving the image name in the database too.
  1. [HttpPost]    
  2. public ActionResult Index(string Imagename)    
  3. {    
  4.     ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();    
  5.     return View();    
  6. } 
Now we will just add a script for calling the Index Action method and passing Imagename as input to it.

We are taking an image name from the image control that we bound when the image was captured.
  1. function Uploadsubmit()   
  2. {  
  3.         debugger;  
  4.         var src = $('img').attr('src');  
  5.         src_array = src.split('/');   
  6.         src = src_array[4];  
  7.         if (src != "") {  
  8.             $.ajax({  
  9.                 type: 'POST',  
  10.                 url: ("@Url.Content("~/Photo/Index")/"),  
  11.                dataType: 'json',  
  12.                data: { Imagename: src },  
  13.                success: function () {  
  14.                }  
  15.            });  
  16. }  
We are calling this uploadsubmit() method on the submit button.
  1. <input id="Submit1" type="submit" onclick="Uploadsubmit();" value="submit" />  


Displaying the index View in New Window

Now I want the index View to display in a new window. For that I will add another action method with the name Changephoto in the same controller.
  1. [HttpGet]    
  2. public ActionResult Changephoto()    
  3. {    
  4.     if (Convert.ToString(Session["val"]) != string.Empty)    
  5.     {    
  6.         ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();    
  7.     }    
  8.     else    
  9.     {    
  10.         ViewBag.pic = "../../WebImages/person.jpg";    
  11.     }    
  12.     return View();    
  13. }  
Inside this Action method I will check whether or not Session[“val”] has a captured Imagename and if not then I display a default image (ViewBag.pic = "../../WebImages/person.jpg"; ) else I will display the captured image ( ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString(); ).

After creating the action method let's add a View to this action method.

Tp add the View just right-click inside the View folder and select Add View. A new dialog will popup for configuring the View. Don't change the name of the View, let it be “Changephoto”. Just click on the Add button.

After clicking on the Add button a new View will be generated in the View folder inside the Photo Folder.

Now inside this View I will add an image control to display the captured image and a button to display the Index View in a new window.

Changephoto.cshtml Code Snippet
  1. @{  
  2.     ViewBag.Title = "Changephoto";  
  3. }  
  4. <script type="text/javascript">  
  5.     function ShowPopUp() {  
  6.         window.open('/Photo/Index/', "wndPopUp", 'width=720,height=400,left=100,top=100,resizable=no');  
  7.     }  
  8. </script>  
  9. <img id="Userpic" src="@ViewBag.pic" />  
  10. <br />  
  11. <input type="button" id="btnSave" value="Take Photo" onclick="ShowPopUp();" />  
After adding the changephoto View let's have a look at PhotoController and Index View Code snippets.

PhotoController Code Snippet
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.IO;  
  7. namespace WebcamMVC.Controllers  
  8. {  
  9.     public class PhotoController : Controller  
  10.     {  
  11.         [HttpGet]  
  12.         public ActionResult Index()  
  13.         {  
  14.             Session["val"] = "";  
  15.             return View();  
  16.         }  
  17.         [HttpPost]  
  18.         public ActionResult Index(string Imagename)  
  19.         {  
  20.                        ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();  
  21.             return View();  
  22.         }  
  23.   
  24.         [HttpGet]  
  25.         public ActionResult Changephoto()  
  26.         {  
  27.             if (Convert.ToString(Session["val"]) != string.Empty)  
  28.             {  
  29.                 ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();  
  30.             }  
  31.             else  
  32.             {  
  33.                 ViewBag.pic = "../../WebImages/person.jpg";  
  34.             }  
  35.             return View();  
  36.         }  
  37.          public JsonResult Rebind()  
  38.         {  
  39.             string path = "http://localhost:55694/WebImages/" + Session["val"].ToString();  
  40.             return Json(path, JsonRequestBehavior.AllowGet);  
  41.         }  
  42.         public ActionResult Capture()  
  43.         {  
  44.             var stream = Request.InputStream;  
  45.             string dump;  
  46.             using (var reader = new StreamReader(stream))  
  47.             {  
  48.                 dump = reader.ReadToEnd();  
  49.                 DateTime nm = DateTime.Now;  
  50.                 string date = nm.ToString("yyyymmddMMss");  
  51.                 var path = Server.MapPath("~/WebImages/" + date + "test.jpg");  
  52.                 System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));  
  53.                 ViewData["path"] = date + "test.jpg";  
  54.                 Session["val"] = date + "test.jpg";  
  55.             }  
  56.             return View("Index");  
  57.         }  
  58.        private byte[] String_To_Bytes2(string strInput)  
  59.         {  
  60.             int numBytes = (strInput.Length) / 2;  
  61.             byte[] bytes = new byte[numBytes];  
  62.             for (int x = 0; x < numBytes; ++x)  
  63.             {  
  64.                 bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);  
  65.             }  
  66.             return bytes;  
  67.         }  
  68.     }  
  69. }  
Index.cshtml Code Snippet
  1. <script type="text/javascript">  
  2.     function UploadPic() {  
  3.         $.ajax({  
  4.             type: 'POST',  
  5.             url: ("@Url.Content("~/Photo/Rebind")/"),  
  6.             dataType: 'json',  
  7.             success: function (data) {  
  8.                 $("#show").attr("src", data);  
  9.                 document.getElementById('Submit1').disabled = false;  
  10.                 alert("Photo Capture successfully!");                  
  11.             }  
  12.         });  
  13.     }  
  14.     function Uploadsubmit() {  
  15.         debugger;  
  16.         var src = $('img').attr('src');  
  17.         src_array = src.split('/');  
  18.         src = src_array[4];  
  19.         if (src != "") {  
  20.             $.ajax({  
  21.                 type: 'POST',  
  22.                 url: ("@Url.Content("~/Photo/Index")/"),  
  23.                dataType: 'json',  
  24.                data: { Imagename: src },  
  25.                success: function () { }  
  26.            });  
  27.             window.opener.location.href = "http://localhost:55694/Photo/Changephoto";  
  28.             self.close();}}  
  29. </script>  
  30. @using (Html.BeginForm())  
  31. {  
  32. @section scripts  
  33. {  
  34.         <script src="@Url.Content("~/Scripts/jquery.webcam.js")">  
  35.         </script>  
  36.         <script type="text/javascript">  
  37.             $("#Camera").webcam({  
  38.                 width: 320,  
  39.                 height: 240,  
  40.                 mode: "save",  
  41.                 swffile: "@Url.Content("~/Scripts/jscam.swf")",  
  42.                 onTick: function () { },  
  43.                 onSave: function () {  
  44.                     UploadPic();  
  45.                 },  
  46.                 onCapture: function () {  
  47.                     webcam.save("@Url.Content("~/Photo/Capture")/");  
  48.              },  
  49.                 debug: function () { },  
  50.                 onLoad: function () { }  
  51.             });  
  52.         </script>  
  53.     }  
  54.     <div style="margin: 0 auto; width: 980px; text-align: center">  
  55.         <div style="float: left; border: 4px solid #ccc; padding: 5px">  
  56.             <div id="Camera"></div><br>  
  57.             <input type="button" value="Capture" onclick="webcam.capture();" />  
  58.         </div>  
  59.         <div style="float: left; margin-left: 20px; border: 4px solid #ccc; padding: 5px">  
  60.             <img id="show" style="width: 320px; height: 240px;" src="../../WebImages/person.jpg" />  
  61.             <br><br>  
  62.             <input id="Submit1" type="submit" onclick="Uploadsubmit();" value="submit" />  
  63.         </div>  
  64.     </div>  
  65.     }  
  66. <script type="text/javascript">  
  67.     window.onload = load();  
  68.     function load() {  
  69.         debugger;  
  70.         document.getElementById('Submit1').disabled = true;  
  71.     }  
  72. </script>  
Finally Output

Now let's run the application and access the changephoto View.



Now just click on the Take photo button and a new window will popup.



Just click on the Allow button.



Now to capture. Just click on the Capture button.





Now click on the Submit button.

After clicking the submit button the popup is closed and an image is set to the Profile picture.



Conclusion

This article showed how to capture an image using webcam.js in MVC in a simple procedure.


Similar Articles