Webcam Barcode Scanner Online with HTML5

If you’re looking to build an online webcam barcode scanner software, you can deploy Dynamsoft Barcode Reader SDK to your web servers (IIS, Apache, Nginx, etc.). Dynamsoft Barcode Reader SDK continuously captures images from your webcam in any HTML5-supported web browsers and sends base64-encoded image data to the cloud barcode service for detection.

As more and more companies embrace cloud services, any desktop applications could be transformed to cloud applications with better maintainability, security, and stability. End-users can use web browsers to get connected with friends, store personal data, watch video, edit documents, publish blog posts, and even write code.

In this article, we take a glimpse of how to make Dynamic Barcode Reader SDK work with web technologies. You will see a cloud-based barcode scanner that consists of a webcam, HTML5-supported web browser, IIS web server, and .NET barcode reader SDK.

Check barcode reading from web camera in C# if you want to implement it in a .NET desktop application.

About Dynamsoft Barcode Reader

Dynamsoft Barcode Reader SDK enables you to efficiently embed barcode reading functionality in your web, desktop and mobile application using just a few lines of code.

Get 30-day free trial 
with sample code included

Supported Programming Languages:

C#,, Java, C++, VB6, Delphi, VBScript, JavaScript, Python, Perl, Ruby, etc.

Implementation of Online Webcam Barcode Reader

See the below video and see how the online webcam barcode reader works:

You can also try the webcam barcode scanner demo below:

Try online demo >

Download the sample code >

Testing Environment

Microsoft Edge, Firefox, Chrome, and Opera.

The Anatomy of Sample Code

  1. Open Visual Studio to create a new web project.
  2. Click References to import Dynamsoft.BarcodeReader.dll.
  3. Create a C# class BarrecodeReaderRepo to handle barcode detection on the server-side:
using System;
using System.Drawing;
using System.IO;
using Dynamsoft.Barcode;

namespace BarcodeDLL
    public class BarrecodeReaderRepo
        private static readonly char CSep = Path.DirectorySeparatorChar;
        private static readonly string StrPath = AppDomain.CurrentDomain.BaseDirectory + "Images";
        private static readonly string CollectFolder = StrPath + CSep + "Collect";

        public static string Barcode(string strImgBase64, Int64 iformat, int iMaxNumbers, ref string strResult)
            if (string.IsNullOrEmpty(strImgBase64.Trim())) throw new Exception("No barcode exist.");

            return DoBarcode(strImgBase64, iformat, iMaxNumbers, ref strResult);

        private static string DoBarcode(string strImgBase64, Int64 format, int iMaxNumbers, ref string strResult)
            strResult = "";
            var strResturn = "[";

            var listResult = GetBarcode(strImgBase64, format, iMaxNumbers);
            if (listResult == null || listResult.Length == 0)
                strResult = "No barcode found. ";
                return "[]";
            strResult = "Total barcode(s) found: " + listResult.Length + "";
            var i = 1;
            foreach (var item in listResult)
                strResult = strResult + "&nbsp&nbspBarcode " + i + ":";
                strResult = strResult + "&nbsp&nbsp&nbsp&nbspType: " + item.BarcodeFormat + "";
                strResult = strResult + "&nbsp&nbsp&nbsp&nbspValue: " + item.BarcodeText + "";
                strResult = strResult + "&nbsp&nbsp&nbsp&nbspRegion: {Left: " + item.ResultPoints[0].X
                            + ", Top: " + item.ResultPoints[0].Y
                            + ", Width: " + item.BoundingRect.Width
                            + ", Height: " + item.BoundingRect.Height + "}";
            strResturn = strResturn.Substring(0, strResturn.Length - 1);
            strResturn += "]";
            return strResturn;

        public static BarcodeResult[] GetBarcode(string strImgBase64, Int64 format, int iMaxNumbers)
            var reader = new Dynamsoft.Barcode.BarcodeReader();
            var options = new ReaderOptions
                MaxBarcodesToReadPerPage = iMaxNumbers,
                BarcodeFormats = (BarcodeFormat) format

            reader.ReaderOptions = options;
            reader.LicenseKeys = "693C401F1CC972A511F060EA05D537CD";
            return reader.DecodeBase64String(strImgBase64);
  1. Create a Generic Handler WebcamBarcodeReader.ashx to process the HTTP request. Parse stream to get the base64 string, and then pass it to BarrecodeReaderRepo:
public class WebcamBarcodeReader : IHttpHandler
        public void ProcessRequest(HttpContext context)
                // 1. Get Base64 Stream
                context.Request.InputStream.Position = 0;
                string jsonString;
                using (var inputStream = new StreamReader(context.Request.InputStream))
                    jsonString = inputStream.ReadToEnd();
                var postData = JsonConvert.DeserializeObject<PostData>(@jsonString);
                if (postData == null) return;
                // 2. reader barcode and output result
                var strResult = "";
                BarrecodeReaderRepo.Barcode(postData.Base64Data, postData.BarcodeType, 10, ref strResult);
                if (strResult.IndexOf("No barcode found", StringComparison.Ordinal) == -1)
                    strResult = "|" + strResult; 

                strResult += DateTime.Now;
            catch (Exception exp)
                context.Response.Write("Error: " + exp.Message);

        public bool IsReusable
                return true;

        public class PostData
            public string Base64Data { get; set; }
            public int BarcodeType { get; set; }
  1. Create an <video></video> element. Open a webcam in a web page with the HTML5 API getUserMedia:
function toggleCamera() {
    var videoSource = videoSelect.value;
    var constraints = {
        video: {
            optional: [{
                sourceId: videoSource


// Start camera preview on <video></video>
function successCallback(stream) { = stream;
    videoElement.src = window.URL.createObjectURL(stream);;

function errorCallback(error) {
    console.log("Error: " + error);

function startCamera(constraints) {
    if (navigator.getUserMedia) {
        navigator.getUserMedia(constraints, successCallback, errorCallback);
    } else {
        console.log("getUserMedia not supported");
  1. How to send preview images to the remote server? Keep drawing frames on a hidden canvas. Convert the canvas data to base64 string and send it in Ajax. If there is nothing detected, use the method setTimeout to send the preview data for detection again:
context.drawImage(videoElement, 0, 0, width, height);
// convert canvas to base64
var base64 = dbrCanvas.toDataURL('image/png', 1.0);
var data = base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "");
var imgData = JSON.stringify({
    Base64Data: data,
    BarcodeType: getBarcodeFormat()
    url: 'WebcamBarcodeReader.ashx',
    dataType: 'json',
    data: imgData,
    type: 'POST',
    complete: function (result) {
        if (isPaused) {
        var barcode_result = document.getElementById('dbr');
        var aryResult;
        aryResult = result.responseText.split('|');

        // display barcode result
        if (result.responseText.indexOf("No barcode") == -1) {
            barcode_result.innerHTML = result.responseText.substring(aryResult[0].length + 1);
        else {
            barcode_result.innerHTML = result.responseText;
            setTimeout(scanBarcode, 200);

Get Free Trial and Samples

Interested in the above-mentioned webcam barcode scanner demo? Download the 30-day free trial of Dynamic Barcode Reader to build your barcode applications.

Get 30-day Free Trial

For more samples about how to use Dynamic Barcode Reader SDK, please visit the code gallery.

The article was posted on codeproject.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe Newsletter

Subscribe to our mailing list to get the monthly update.