Introduction
This code helps you to capture a photo without using a flash player in HTML5, and save a photo using ASP.NET and MVC
HTML 5 Code to enable and view camera
- <div style="float: left; border: 4px solid #ccc; padding: 5px">
- <video autoplay width="480" height="360"></video>
- <button id="live" style="cursor:pointer">
- Enable Camera
- </button>
- <button id="snap" style="cursor:pointer">
- Capture Photo
- </button>
- <img style="vertical-align:top" id="imgCapture" width="480" height="360" />
- </div>
"Enable Camera" is a button, to enable camera with video in the application. To enable camera, below is the Javascript required and the video will be appear in the <Video></Video> tag section.
- const video = document.querySelector('video')
- document.getElementById('live').onclick = function () {
- navigator.mediaDevices.getUserMedia({
- video: true
- }).then(stream => video.srcObject = stream);
- };
-
- const canvas = document.createElement('canvas');
- const img = document.querySelector('img');
"CAPTURE PHOTO" - is a button to capture photo from the video playing the <Video></Video> tag section and the photo will be displayed in the ID - "imgCapture" section. Javascript below:
- document.getElementById('snap').onclick = function () {
- canvas.width = video.videoWidth;
- canvas.height = video.videoHeight;
- canvas.getContext('2d').drawImage(video, 0, 0);
- video.srcObject.getTracks().forEach(track => track.stop());
-
- $("#imgCapture").css("visibility", "visible");
- $("#imgCapture").attr("src", canvas.toDataURL('image/png'));
- $('#capture_photo').val(canvas.toDataURL('image/png'));
- PostImage();
- }
"PostImage()" - is a javascript method, which will call MVC action method to save the captured photo physically in the application folder.
- function PostImage() {
- var photoVal = $('#imgCapture').val();
- if (photoVal != "") {
- $.ajax({
- type: "POST",
- url: '/BasicClaimant/PhotoCapture',
- async: false,
- data: { photoVal: photoVal },
- contentType: "application/html; charset=utf-8",
- dataType: "text",
- success: function (r) {
- $("#imgCapture").css("visibility", "visible");
- $("#imgCapture").attr("src", r);
- $('#capture_photo').val(r);
-
- },
- failure: function (response) {
- alert(response.d);
- }
- });
- }
-
- }
Please find the MVC ASP.NET C# code to save the photo in a physical folder
- public ActionResult PhotoCapture()
- {
- if (!System.IO.Directory.Exists(Server.MapPath("~/Captures")))
- {
- System.IO.Directory.CreateDirectory(Server.MapPath("~/Captures"));
- }
- if (Request.InputStream.Length > 0)
- {
- using (StreamReader reader = new StreamReader(Request.InputStream))
- {
- string hexString = Server.UrlEncode(reader.ReadToEnd());
- string imagePath = string.Format("~/Captures/{0}.png", imageName);
- System.IO.File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(hexString));
- }
- }
-
- }
Thank you for reading!