
In this modern era of smartphones, everyone has a cool camera which has also been used by many apps and web applications to capture profile pictures as we are moving towards new technologies, i.e., ASP.NET Core MVC. Let’s have a look at how we can achieve this functionally in it.
Agenda
- Create ASP.NET Core MVC application.
- Download and Adding webcam.js related reference files to project.
- Adding Controller (camera controller).
- Adding Capture view.
- Adding Action Method Capture for Handling Ajax Post request
- Capture Image in Debug Mode
- Storing Captured Image in a folder
- Storing Captured Image in Database
- Complete Code Snippet of the camera controller
- Complete Code Snippet of Capture.cshtml
- Finally Get The Output.
Creating ASP.NET Core MVC application
In this part, we are going to create an ASP.NET CORE MVC application and name it as “DemoWebCam”.

After naming it, just click on the OK button. A new dialog will then pop up for selecting a template. Select the Web Application (Model-View-Controller) 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.
Download and Adding webcam.js related reference files to project
In this part, we are going to download the webcam.js script from this path https://github.com/jhuckaby/webcamjs and add it to our “wwwroot” folder such that we can reference it on the View.
Note
In ASP.NET Core, whatever static files you want to access on the browser, those must be kept in the “wwwroot” folder.

After adding the files, let's move to add a Controller.
Adding Controller (CameraController)
In this part, we are going to add a controller with the name “Camera” (“CameraController”).

CodeSnippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- namespace DemoWebCam.Controllers
- {
- public class CameraController : Controller
- {
- public IActionResult Capture()
- {
- return View();
- }
- }
- }
After adding a Camera Controller, next, we are going to change the name of the Index action method to capture.
Now, let's add a View to this Capture action method.
Adding Capture View
In this part, we are going to add Capture View. To add a View, just right click inside the “Capture” action method, a new dialog will pop up for configuring the View. In that, we are going to just enter the View name as “Capture” and uncheck the layout checkbox.

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 Capture View
- <div class="col-md-2"></div>
- <div class="col-md-4">
- <div class="panel panel-default">
- <div class="panel-heading">Camera</div>
- <div class="panel-body">
- <div id="my_camera"></div>
- <!-- A button for taking snaps -->
- <form>
- <input type="button" class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
- </form>
- </div>
- </div>
- </div>
- <div class="col-md-4">
- <div class="panel panel-default">
- <div class="panel-heading">Captured Photo</div>
- <div class="panel-body">
- <div id="results">Your captured image will appear here...</div>
- </div>
- <br />
- <br />
- </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.
- <!-- Configure a few settings and attach camera -->
- <script language="JavaScript">
- Webcam.set({
- width: 320,
- height: 240,
- image_format: 'jpeg',
- jpeg_quality: 90
- });
- Webcam.attach('#my_camera');
- </script>
- <!-- Code to handle taking the snapshot and displaying it locally -->
- <script language="JavaScript">
- function take_snapshot() {
- // take snapshot and get image data
- Webcam.snap(function (data_uri) {
- // display results in page
- document.getElementById('results').innerHTML =
- '<img src="' +
- data_uri +
- '"/>';
- Webcam.upload(data_uri,
- '/Camera/Capture',
- function (code, text) {
- alert('Photo Captured');
- });
- });
- }
- </script>
Now, let’s run the application to confirm that your capture View is working accurately.

Adding Action Method Capture for Handling Ajax Post request
For capturing an image, we are going to add Capture Action Method which will handle post request.
After that, we are going to read values from Request (HttpContext.Request.Form.Files) next we are going to create a unique name to this image which we have captured and store it in “CameraPhotos” folder which we have created in the "wwwroot" folder.

Code Snippet of Capture Action Method
- [HttpPost]
- public IActionResult Capture(string name)
- {
- var files = HttpContext.Request.Form.Files;
- if (files != null)
- {
- foreach (var file in files)
- {
- if (file.Length > 0)
- {
- // Getting Filename
- var fileName = file.FileName;
- // Unique filename "Guid"
- var myUniqueFileName = Convert.ToString(Guid.NewGuid());
- // Getting Extension
- var fileExtension = Path.GetExtension(fileName);
- // Concating filename + fileExtension (unique filename)
- var newFileName = string.Concat(myUniqueFileName, fileExtension);
- // Generating Path to store photo
- var filepath = Path.Combine(_environment.WebRootPath, "CameraPhotos") + $@"\{newFileName}";
- if (!string.IsNullOrEmpty(filepath))
- {
- // Storing Image in Folder
- StoreInFolder(file, filepath);
- }
- var imageBytes = System.IO.File.ReadAllBytes(filepath);
- if (imageBytes != null)
- {
- // Storing Image in Folder
- StoreInDatabase(imageBytes);
- }
- }
- }
- return Json(true);
- }
- else
- {
- return Json(false);
- }
- }
Now, let us complete with adding capture Action Method to handle the post Request.
Let’s run the application and have a look at it in debug mode.
Capture Image in Debug Mode at Client Side

When we click on the Capture button, it calls “take_snapshot” function of JavaScript in which we get the base64 format of a captured image which is shown in detail below.

After capturing, the base64 string is uploaded to Capture Action Method.

The Capture Action Method after receiving the request.

Snapshot after capturing the image successfully.

Storing Captured Image in folder
- /// <summary>
- /// Saving captured image into Folder.
- /// </summary>
- /// <param name="file"></param>
- /// <param name="fileName"></param>
- private void StoreInFolder(IFormFile file, string fileName)
- {
- using (FileStream fs = System.IO.File.Create(fileName))
- {
- file.CopyTo(fs);
- fs.Flush();
- }
- }
Debug Mode while storing the image in folder.

Folder view where Images are stored after capturing

After storing the image in the folder, next, we are going to store the image in the database.
Storing Captured Image in Database
In this part, we are going see step by step how to store Base64String in the database.
ImageStore Table

After having a look at table design next we are going to create a Model with the same column name and datatypes in the Models folder.
ImageStore Model
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Linq;
- using System.Threading.Tasks;
- namespace DemoWebCam.Models
- {
- [Table("ImageStore")]
- public class ImageStore
- {
- [Key]
- public int ImageId { get; set; }
- public string ImageBase64String { get; set; }
- public DateTime? CreateDate { get; set; }
- }
- }
After adding Model, Next, we are going to Add DatabaseContext to store Image into the database.
Adding DatabaseContext
In this part, we are going to add DatabaseContext class in “EntityStore” folder.
After adding DatabaseContext class we are going to inherit DatabaseContext class from DbContext Class and declare entity (“ImageStore”) in it.
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using DemoWebCam.Models;
- using Microsoft.EntityFrameworkCore;
- namespace DemoWebCam.EntityStore
- {
- public class DatabaseContext : DbContext
- {
- public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
- {
- }
- public DbSet<ImageStore> ImageStore { get; set; }
- }
- }
After adding DatabaseContext Class, next we are going to Configure Connection string in appsettings.json.
View of appsettings.json
- {
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "ConnectionStrings": {
- "DefaultConnection": "Data Source=SAI-PC\\SQLEXPRESS; UID=sa; Password=Pass$123;Database=TESTDB;"
- }
- }
Finally, we are in the last part for storing the image into the database. We just need to configure service in Startup.cs class for injecting connection string.
Startup.cs class

Now we are ready to store images into the database.
Below is code which we are going to use for storing the image into the database.
In this part, we have created a separate method “StoreInDatabase” which takes image bytes as input. After taking bytes as input, next for storing in the database we are going to convert these bytes to base64string.
Code Snippet for storing Base64String into database
- /// <summary>
- /// Saving captured image into database.
- /// </summary>
- /// <param name="imageBytes"></param>
- private void StoreInDatabase(byte[] imageBytes)
- {
- try
- {
- if (imageBytes != null)
- {
- string base64String = Convert.ToBase64String(imageBytes, 0, imageBytes.Length);
- string imageUrl = string.Concat("data:image/jpg;base64,", base64String);
- ImageStore imageStore = new ImageStore()
- {
- CreateDate = DateTime.Now,
- ImageBase64String = imageUrl,
- ImageId = 0
- };
- _context.ImageStore.Add(imageStore);
- _context.SaveChanges();
- }
- }
- catch (Exception)
- {
- throw;
- }}
Debug Mode while storing Image in the database.

After Storing Image in Database

After storing the image in database, next, let’s see the complete code snippet view of Controller and View.
Complete Code Snippet of CameraController
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using DemoWebCam.EntityStore;
- using DemoWebCam.Models;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- namespace DemoWebCam.Controllers
- {
- public class CameraController : Controller
- {
- private readonly DatabaseContext _context;
- private readonly IHostingEnvironment _environment;
- public CameraController(IHostingEnvironment hostingEnvironment, DatabaseContext context)
- {
- _environment = hostingEnvironment;
- _context = context;
- }
- [HttpGet]
- public IActionResult Capture()
- {
- return View();
- }
- [HttpPost]
- public IActionResult Capture(string name)
- {
- var files = HttpContext.Request.Form.Files;
- if (files != null)
- {
- foreach (var file in files)
- {
- if (file.Length > 0)
- {
- // Getting Filename
- var fileName = file.FileName;
- // Unique filename "Guid"
- var myUniqueFileName = Convert.ToString(Guid.NewGuid());
- // Getting Extension
- var fileExtension = Path.GetExtension(fileName);
- // Concating filename + fileExtension (unique filename)
- var newFileName = string.Concat(myUniqueFileName, fileExtension);
- // Generating Path to store photo
- var filepath = Path.Combine(_environment.WebRootPath, "CameraPhotos") + $@"\{newFileName}";
- if (!string.IsNullOrEmpty(filepath))
- {
- // Storing Image in Folder
- StoreInFolder(file, filepath);
- }
- var imageBytes = System.IO.File.ReadAllBytes(filepath);
- if (imageBytes != null)
- {
- // Storing Image in Folder
- StoreInDatabase(imageBytes);
- }
- }
- }
- return Json(true);
- }
- else
- {
- return Json(false);
- }
- }
- /// <summary>
- /// Saving captured image into Folder.
- /// </summary>
- /// <param name="file"></param>
- /// <param name="fileName"></param>
- private void StoreInFolder(IFormFile file, string fileName)
- {
- using (FileStream fs = System.IO.File.Create(fileName))
- {
- file.CopyTo(fs);
- fs.Flush();
- }
- }
- /// <summary>
- /// Saving captured image into database.
- /// </summary>
- /// <param name="imageBytes"></param>
- private void StoreInDatabase(byte[] imageBytes)
- {
- try
- {
- if (imageBytes != null)
- {
- string base64String = Convert.ToBase64String(imageBytes, 0, imageBytes.Length);
- string imageUrl = string.Concat("data:image/jpg;base64,", base64String);
- ImageStore imageStore = new ImageStore()
- {
- CreateDate = DateTime.Now,
- ImageBase64String = imageUrl,
- ImageId = 0
- };
- _context.ImageStore.Add(imageStore);
- _context.SaveChanges();
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- }
Complete Code Snippet of Capture.cshtml View
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>WebcamJS Test Page</title>
- <link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
- <style type="text/css">
- body {
- font-family: Helvetica, sans-serif;
- }
- h2, h3 {
- margin-top: 0;
- }
- form {
- margin-top: 15px;
- }
- form > input {
- margin-right: 15px;
- }
- #buttonhide {
- background: transparent;
- border: none !important;
- font-size: 0;
- }
- </style>
- </head>
- <body class="container">
- <br />
- <div class="col-md-2"></div>
- <div class="col-md-4">
- <div class="panel panel-default">
- <div class="panel-heading">Camera</div>
- <div class="panel-body">
- <div id="my_camera"></div>
- <!-- A button for taking snaps -->
- <form>
- <input type="button" class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
- </form>
- </div>
- </div>
- </div>
- <div class="col-md-4">
- <div class="panel panel-default">
- <div class="panel-heading">Captured Photo</div>
- <div class="panel-body">
- <div id="results">Your captured image will appear here...</div>
- </div>
- <br />
- <br />
- </div>
- </div>
- <div class="col-md-2"> </div>
- <!-- First, include the Webcam.js JavaScript Library -->
- <script src="~/webcamjs/webcam.js"></script>
- <!-- Configure a few settings and attach camera -->
- <script language="JavaScript">
- Webcam.set({
- width: 320,
- height: 240,
- image_format: 'jpeg',
- jpeg_quality: 90
- });
- Webcam.attach('#my_camera');
- </script>
- <!-- Code to handle taking the snapshot and displaying it locally -->
- <script language="JavaScript">
- function take_snapshot() {
- // take snapshot and get image data
- Webcam.snap(function (data_uri) {
- // display results in page
- document.getElementById('results').innerHTML =
- '<img src="' +
- data_uri +
- '"/>';
- Webcam.upload(data_uri,
- '/Camera/Capture',
- function (code, text) {
- alert('Photo Captured');
- });
- });
- }
- </script>
- </body>
- </html>
After having a complete view of the Controller and View Code snippet, let's run the application to do final testing.
Finally Output
In this part, we have the capture image which is stored in the folder as well as the database successfully.

Displays alert after capturing Image.

Conclusion
In this article we have learned how to capturing image from Web Cam in ASP.Net Core MVC using webcam.js, and how to store the image in a folder and database in a step by step way.

Nidhi PaneriPosted Dec 3, 2021, 7:46 AM
How can we use rear camera in this?
Sanjay ShekhawatPosted May 22, 2021, 12:37 PM
Thanks for Sharing...
Adrian BaptistaPosted Sep 6, 2020, 12:09 AM
Its works fine ... thank you for this useful code
Troydon LuicienPosted Aug 1, 2020, 12:18 AM
Took so much time trying to debug why it would not work when I tried to add it to an existing controller, gave up and will assume it is something to do with the return data clashing from another form that uses the same action method. But anyway, this is awesome, now I can take a step forward towards implementing my facial recognition.
pee geePosted Jul 19, 2020, 3:28 PM
Thanks. short sweet. perfect.
Abdul K SiddiquiPosted Jul 2, 2020, 11:07 AM
Hi Saineshwar, thank you for such a nice project.
Megha KadamPosted May 13, 2020, 9:33 AM
Hi Sir, really it's working fine, now i want to add some other fields also in this, so in which method need to add new code, can you suggest?
Alex MusumeciPosted Apr 12, 2020, 10:40 PM
Thanks for the blog man. Very helpful and simple solution.
Komal GroverPosted Jun 13, 2019, 2:47 PM
Camera does not switch off after capturing one image
Vaishnavi KulkarniPosted Mar 18, 2019, 8:01 AM
Hi Saineshwar, will it work with mobile camera?
Alice NguyenPosted Jan 29, 2019, 10:09 PM
Hi Saineshwar BageriI downloaded your sources code. Project warning: One or more projects in the solution was not loaded correctly. Please see the Windows Output for details How to fix the warning? VS 2015 is used Thanks and regards, Alice Nguyen
Alice NguyenPosted Jan 29, 2019, 3:07 AM
Nice article, thank you.
Ali MumtazPosted Dec 24, 2018, 8:02 AM
Excellent tutorial......i need to know if i can have a name field to save image with given name in the name field?
Fredy GonzalesPosted Oct 30, 2018, 9:15 PM
Excelente, Gracias!!!
Tochi NickyPosted Oct 21, 2018, 5:24 AM
Nice tutorial.. please how can I add user name,email etc and still post it to the database. Thanks
Munesh SharmaPosted Sep 16, 2018, 4:16 AM
Nice article to explain such type of functionality ... :)
Arun Kumar SinghPosted Sep 15, 2018, 4:43 AM
Awesome keep it up Sir
Ankur MistryPosted Sep 15, 2018, 4:01 AM
Always waiting for your article. Thanks for sharing
Prabu ElavarasanPosted Sep 14, 2018, 10:14 PM
Interesting.Bookmarked.. Thanks much for the good article.. Please keep posted....
Debasis SahaPosted Sep 14, 2018, 9:27 PM
Great article Sir... Thanks for Sharing...
Sarathlal SaseendranPosted Sep 14, 2018, 10:38 AM
Its very useful. Thanks for sharing