Click here to Skip to main content
13,146,742 members (79,950 online)
Click here to Skip to main content
Add your own
alternative version

Stats

24.5K views
7 bookmarked
Posted 16 May 2016

Webcam Barcode Scanner with HTML5 and Web Browser

, 16 May 2016
How to build a webcam barcode scanner for cloud service?Deploy Dynamic Barcode Reader SDK to your web servers (IIS, Apache, Nginx, etc.). Continuously capture images from your webcam in any HTML5-supported webbrowsers and send base64-encoded image data to the cloud barcode service fordetection.

Editorial Note

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Introduction

As Internet connection speed getting faster, more and more people tend to embrace cloud service. 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 social friends, store tons of personal data, watch live video, edit documents, publish blog posts and even write code. In this article, we will 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.

Why Dynamsoft Barcode Reader

Supported 1D/2D Barcode Types

  • 1D: Code 39, Code 93, Code 128, Codabar, EAN-8, EAN-13, UPC-A, UPC-E, Interleaved 2 of 5 (ITF), Industrial 2 of 5 (Code 2 of 5 Industry, Standard 2 of 5, Code 2 of 5), ITF-14
  • 2D: QRCode, DataMatrix, and PDF417

Supported Image Types

  • BMP, JPEG, PNG, GIF, TIFF, and PDF

Detected Barcode Information

  • Barcode type
  • Barcode count
  • Barcode value as string
  • Barcode raw data as bytes
  • Barcode bounding rectangle
  • Coordinate of four corners
  • Page number

Features

  • Accurate: reads barcodes within a specified area of a selected image.
  • Effective: reads multiple barcodes in one image.
  • Powerful: reads poor quality and damaged barcodes.
  • Flexible: detects barcode at any orientation and rotation angle.

Supported Programming Languages

  • C#, VB.net, Java, C++, PHP, JavaScript, Python and etc.

Implementation of Webcam Barcode Scanner

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 + "}";
                i++;
            }
            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)
        {
            try
            {
                // 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;
                context.Response.Write(strResult);
            }
            catch (Exception exp)
            {
                context.Response.Write("Error: " + exp.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

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

    startCamera(constraints);
}

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

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()
});
$.ajax({
    url: 'WebcamBarcodeReader.ashx',
    dataType: 'json',
    data: imgData,
    type: 'POST',
    complete: function (result) {
        console.log(result);
        if (isPaused) {
            return;
        }
        var barcode_result = document.getElementById('dbr');
        var aryResult;
        aryResult = result.responseText.split('|');

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

Online Demo

Try it now!

Get SDK 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.
Dynamic Barcode Reader 30-day Free Trial

For more samples about how to use Dynamic Barcode Reader SDK, please visit the following page:
Dynamic Barcode Reader Demos

One More Thing

Dynamsoft Barcode Reader SDK is not only available for Windows, but also for Linux and Mac OS X. You can have fun with it on your favorite platform. If you have any questions, please feel free to contact support@dynamsoft.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dynamsoft
Canada Canada
Dynamsoft has more than 10 years of experience in TWAIN SDKs, imaging SDKs and version control solutions.

Our products include:

TWAIN SDK
- Dynamic Web TWAIN: a TWAIN scanning SDK optimized for web document management applications.
- Dynamic .NET TWAIN: a .NET TWAIN and Directshow Image Capture SDK for WinForms/WPF applications.

Imaging SDKs
- Barcode Reader for Windows, Linux, macOS, iOS, Android and Raspberry Pi.
- OCR addon for both web and .NET TWAIN SDKs

Version Control
- SourceAnywhere: a SQL server-based source control solution. Both on-premise and hosting options are provided.
Group type: Organisation

20 members


You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 16 May 2016
Article Copyright 2016 by Dynamsoft
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid