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
- Create basic MVC application.
- Download and Adding webcam.js related reference files to project.
- Adding Controller ( PhotoController ).
- Adding Index view.
- Adding Action Method Capture( ).
- Adding Script for capturing Image.
- Adding Action Method and Script for binding image.
- Adding [HttpPost] Index Action Method.
- Displaying the index View in New Window.
- Changephoto.cshtml Code Snippet.
- PhotoController Code Snippet.
- Index.cshtml Code Snippet.
- 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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.IO;
- namespace WebcamMVC.Controllers
- {
- public class PhotoController : Controller
- {
- [HttpGet]
- public ActionResult Index()
- {
- return View();
- }
- }
- }
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
- <div style="margin: 0 auto; width: 980px; text-align: center">
- <div style="float: left; border: 4px solid #ccc; padding: 5px">
- <div id="Camera">
- </div>
- <br>
- <input type="button" value="Capture" />
- </div>
- <div style="float: left; margin-left: 20px; border: 4px solid #ccc; padding: 5px">
- <img id="show" style="width: 320px; height: 240px;" src="../../WebImages/person.jpg" />
- <br>
- <br>
- <input id="Submit1" type="submit" value="submit" />
- </div>
- </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.
- @section scripts
- {
- <script src="@Url.Content("~/Scripts/jquery.webcam.js")">
- </script>
- <script type="text/javascript">
- $("#Camera").webcam({
- width: 320,
- height: 240,
- mode: "save",
- swffile: "@Url.Content("~/Scripts/jscam.swf")",
- onTick: function () { },
- onSave: function () {
- UploadPic();
- },
- onCapture: function () {
- webcam.save("@Url.Content("~/Photo/Capture")/");
- },
- debug: function () { },
- onLoad: function () { }
-
- });
-
- </script>
- }
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
- public ActionResult Capture()
- {
- var stream = Request.InputStream;
- string dump;
- using (var reader = new StreamReader(stream))
- {
- dump = reader.ReadToEnd();
- DateTime nm = DateTime.Now;
- string date = nm.ToString("yyyymmddMMss");
- var path = Server.MapPath("~/WebImages/" + date + "test.jpg");
- System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));
- ViewData["path"] = date + "test.jpg";
- Session["val"] = date + "test.jpg";
- }
- return View("Index");
- }
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.
- private byte[] String_To_Bytes2(string strInput)
- {
- int numBytes = (strInput.Length) / 2;
- byte[] bytes = new byte[numBytes];
- for (int x = 0; x < numBytes; ++x)
- {
- bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
- }
- return bytes;
- }
Adding Script for capturing ImageThis Script will capture an image.
- @section scripts
- {
- <script src="@Url.Content("~/Scripts/jquery.webcam.js")">
- </script>
- <script type="text/javascript">
- $("#Camera").webcam({
- width: 320,
- height: 240,
- mode: "save",
- swffile: "@Url.Content("~/Scripts/jscam.swf")",
- onTick: function () { },
- onSave: function () {
- UploadPic();
- },
- onCapture: function () {
- webcam.save("@Url.Content("~/Photo/Capture")/");
- },
- debug: function () { },
- onLoad: function () { }
- });
- </script>
- }
- onCapture: function () {
- webcam.save("@Url.Content("~/Photo/Capture")/");
- },
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();
- <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 imageFor binding the image I wrote a JSON method with the name
Rebind that will be called when I click on the Capture button.
- public JsonResult Rebind()
- {
- string path = "http://localhost:55694/WebImages/" + Session["val"].ToString();
- return Json(path, JsonRequestBehavior.AllowGet);
- }
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.
- function UploadPic() {
- $.ajax({
- type: 'POST',
- url: ("@Url.Content("~/Photo/Rebind")/"),
- dataType: 'json',
- success: function (data) {
- $("#show").attr("src", data);
- document.getElementById('Submit1').disabled = false;
- alert("Photo Capture successfully!");
- }
- });
- }
Similarly we are calling the UploadPic() function in the webcam script.
- onSave: function ()
- {
- UploadPic();
- },
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.
- [HttpPost]
- public ActionResult Index(string Imagename)
- {
- ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();
- return View();
- }
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.
- function Uploadsubmit()
- {
- debugger;
- var src = $('img').attr('src');
- src_array = src.split('/');
- src = src_array[4];
- if (src != "") {
- $.ajax({
- type: 'POST',
- url: ("@Url.Content("~/Photo/Index")/"),
- dataType: 'json',
- data: { Imagename: src },
- success: function () {
- }
- });
- }
We are calling this uploadsubmit() method on the submit button.
- <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.
- [HttpGet]
- public ActionResult Changephoto()
- {
- if (Convert.ToString(Session["val"]) != string.Empty)
- {
- ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();
- }
- else
- {
- ViewBag.pic = "../../WebImages/person.jpg";
- }
- return View();
- }
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
- @{
- ViewBag.Title = "Changephoto";
- }
- <script type="text/javascript">
- function ShowPopUp() {
- window.open('/Photo/Index/', "wndPopUp", 'width=720,height=400,left=100,top=100,resizable=no');
- }
- </script>
- <img id="Userpic" src="@ViewBag.pic" />
- <br />
- <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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.IO;
- namespace WebcamMVC.Controllers
- {
- public class PhotoController : Controller
- {
- [HttpGet]
- public ActionResult Index()
- {
- Session["val"] = "";
- return View();
- }
- [HttpPost]
- public ActionResult Index(string Imagename)
- {
- ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();
- return View();
- }
-
- [HttpGet]
- public ActionResult Changephoto()
- {
- if (Convert.ToString(Session["val"]) != string.Empty)
- {
- ViewBag.pic = "http://localhost:55694/WebImages/" + Session["val"].ToString();
- }
- else
- {
- ViewBag.pic = "../../WebImages/person.jpg";
- }
- return View();
- }
- public JsonResult Rebind()
- {
- string path = "http://localhost:55694/WebImages/" + Session["val"].ToString();
- return Json(path, JsonRequestBehavior.AllowGet);
- }
- public ActionResult Capture()
- {
- var stream = Request.InputStream;
- string dump;
- using (var reader = new StreamReader(stream))
- {
- dump = reader.ReadToEnd();
- DateTime nm = DateTime.Now;
- string date = nm.ToString("yyyymmddMMss");
- var path = Server.MapPath("~/WebImages/" + date + "test.jpg");
- System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump));
- ViewData["path"] = date + "test.jpg";
- Session["val"] = date + "test.jpg";
- }
- return View("Index");
- }
- private byte[] String_To_Bytes2(string strInput)
- {
- int numBytes = (strInput.Length) / 2;
- byte[] bytes = new byte[numBytes];
- for (int x = 0; x < numBytes; ++x)
- {
- bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
- }
- return bytes;
- }
- }
- }
Index.cshtml Code Snippet
- <script type="text/javascript">
- function UploadPic() {
- $.ajax({
- type: 'POST',
- url: ("@Url.Content("~/Photo/Rebind")/"),
- dataType: 'json',
- success: function (data) {
- $("#show").attr("src", data);
- document.getElementById('Submit1').disabled = false;
- alert("Photo Capture successfully!");
- }
- });
- }
- function Uploadsubmit() {
- debugger;
- var src = $('img').attr('src');
- src_array = src.split('/');
- src = src_array[4];
- if (src != "") {
- $.ajax({
- type: 'POST',
- url: ("@Url.Content("~/Photo/Index")/"),
- dataType: 'json',
- data: { Imagename: src },
- success: function () { }
- });
- window.opener.location.href = "http://localhost:55694/Photo/Changephoto";
- self.close();}}
- </script>
- @using (Html.BeginForm())
- {
- @section scripts
- {
- <script src="@Url.Content("~/Scripts/jquery.webcam.js")">
- </script>
- <script type="text/javascript">
- $("#Camera").webcam({
- width: 320,
- height: 240,
- mode: "save",
- swffile: "@Url.Content("~/Scripts/jscam.swf")",
- onTick: function () { },
- onSave: function () {
- UploadPic();
- },
- onCapture: function () {
- webcam.save("@Url.Content("~/Photo/Capture")/");
- },
- debug: function () { },
- onLoad: function () { }
- });
- </script>
- }
- <div style="margin: 0 auto; width: 980px; text-align: center">
- <div style="float: left; border: 4px solid #ccc; padding: 5px">
- <div id="Camera"></div><br>
- <input type="button" value="Capture" onclick="webcam.capture();" />
- </div>
- <div style="float: left; margin-left: 20px; border: 4px solid #ccc; padding: 5px">
- <img id="show" style="width: 320px; height: 240px;" src="../../WebImages/person.jpg" />
- <br><br>
- <input id="Submit1" type="submit" onclick="Uploadsubmit();" value="submit" />
- </div>
- </div>
- }
- <script type="text/javascript">
- window.onload = load();
- function load() {
- debugger;
- document.getElementById('Submit1').disabled = true;
- }
- </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.