A complete post on how to Take a Picture with a Webcam in ASP.NET Core. It covers both front-end and back-end code for ASP.NET Core MVC or Razor Pages.
Prerequisites- .NET SDK (7 or later recommended)
- Basic knowledge of ASP.NET Core (MVC or Razor Pages)
- A webcam device connected to your computer
Take a Pic with Webcam in ASP.NET Core
Getting Started
Taking a picture with a webcam in a web application is a common requirement in modern web apps — whether it's for a user profile, attendance system, or any identity verification process.
Here we will learn how to take a picture with webcam using ASP.NET Core. To take a photo and display the live webcam stream on a web page, we will use the WebRTC API)
- Display live streaming from a webcam
- Capture photo frame from live streaming
- Save the captured photo on server
Fron-end Code: Index.chtml
or Razor Page
The following code example is for access Webcam with HTML and JavaScript to show the webcam feed and a button to capture the image.
@{
ViewData["Title"] = "Webcam Capture";
}
<h2>Webcam Capture</h2>
<video id="video" width="640" height="480" autoplay></video>
<br />
<button id="captureBtn">Capture</button>
<canvas id="canvas" width="640" height="480" style="display: none;"></canvas>
<img id="photo" alt="Captured Image" />
<form id="uploadForm">
<input type="hidden" name="imageData" id="imageData" />
<button type="submit">Save Photo</button>
</form>
@section Scripts {
<script>
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const photo = document.getElementById('photo');
const imageDataInput = document.getElementById('imageData');
// Ask for permission to access webcam
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
video.srcObject = stream;
})
.catch(err => {
console.error("Error accessing webcam: ", err);
});
document.getElementById('captureBtn').addEventListener('click', () => {
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const imageDataURL = canvas.toDataURL('image/png');
photo.src = imageDataURL;
imageDataInput.value = imageDataURL;
});
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('imageData', imageDataInput.value);
const response = await fetch('/Home/SavePhoto', {
method: 'POST',
body: formData
});
if (response.ok) {
alert('Photo saved successfully!');
} else {
alert('Error saving photo.');
}
});
</script>
}
Back-end code: Handle Photo Upload
Create an endpoint in your Controller or PageMode class to accept and save the image.
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Text.RegularExpressions;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SavePhoto(string imageData)
{
if (string.IsNullOrEmpty(imageData))
{
return BadRequest("No image data received.");
}
// Extract base64 content
var base64Data = Regex.Match(imageData, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
byte[] imageBytes = Convert.FromBase64String(base64Data);
// Generate unique filename
string fileName = $"photo_{DateTime.Now:yyyyMMddHHmmss}.png";
string savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images");
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
System.IO.File.WriteAllBytes(Path.Combine(savePath, fileName), imageBytes);
return Ok(new { fileName });
}
}
Summary
Capturing webcam photos in ASP.NET Core is relatively straightforward with the help of HTML5
, JavaScript
, and a simple backend controller. With this setup, you now have a working prototype for webcam-based photo capture and storage.
Thanks