Barcode Recognition SDK

Happy Mahashivratri All. I`m back to my blog to add few learning from my past experiences.

These days, we are using the barcode anywhere for code scanning and doing the process automation as much as much possible.

For that we can use the Dynamsoft Barcode Recognition SDK. I have attached some code samples for HTML, JS and C# code for the same.

HMTL:

<%@ Page Title=”Merchant QR Code” MasterPageFile=”~/Site.Master” Language=”C#” AutoEventWireup=”true” CodeBehind=”CustomerQRScanner.aspx.cs” Inherits=”Merchant.CustomerQRScanner” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”head” runat=”server”>
<%–<link href=”Content/basis-bs.css” rel=”stylesheet” type=”text/css” />
<link href=”Content/head.css” rel=”stylesheet” />–%>
</asp:Content>
<asp:Content ID=”BodyContent” ContentPlaceHolderID=”MainContent” runat=”server”>

<div class=”container”>
<div class=”row” style=”text-align: center”>
<div class=”col-md-4″>
<div class=”row”>
<br />
<h2>To confirm transaction:</h2>
<p style=”font-size: smaller; font-weight: bold”>Point your smartphone camera at QR code…</p>
<br />

<div class=”form-group” style=”border: 1px solid #ddd;”>
<video style=”width: 100%; height: 100%;”></video>

<div id=”videoOption” style=”display: none;”>
<span>Camera Sources: &nbsp;</span>
<select id=”videoSource”></select>
<div id=”divErrInfo”></div>

</div>
<%–<video style=”width: 100%; height: 100%;” muted webkit-playsinline=”true”></video>–%>
</div>

<div style=”display: none”>
<input id=”chkLinear” name=”BarcodeType” type=”checkbox” value=”0x3FF” checked=”true” onclick=”ClickCheckBox(this);” />
<input id=”chkQRCode” name=”BarcodeType” type=”checkbox” value=”0x4000000″ checked=”true” onclick=”ClickCheckBox(this);” />
<input id=”chkPdf” name=”BarcodeType” type=”checkbox” value=”0x2000000″ checked=”true” onclick=”ClickCheckBox(this);” />
<input id=”chkDM” name=”BarcodeType” type=”checkbox” value=”0x8000000″ checked=”true” onclick=”ClickCheckBox(this);” />

<button id=”go” style=”margin-bottom: 12.5px;”>Read Barcode</button>

<div>
<div id=”dbr”></div>
<img id=”image” width=”320″ height=”240″ style=”display: none;” />
</div>

<canvas id=”pcCanvas” width=”640″ height=”480″ style=”display: none;”></canvas>
</div>

</div>
<%–<div class=”row”>
<br />
<asp:LinkButton ID=”li_cancelTrans” runat=”server” OnClick=”li_cancelTrans_Click”>Cancel Transaction</asp:LinkButton>
</div>–%>
</div>
</div>
</div>
http://Scripts/Dynamsoft.BarcodeReaderDemo.js
http://Scripts/video.js?3
<script>
$(document).ready(function () {
document.getElementById(“go”).click();
});
</script>
</asp:Content>

 

Dynamsoft.BarcodeReaderDemo.js:

var Dynamsoft = {};
Dynamsoft.BarcodeReaderDemo = {};

Dynamsoft.BarcodeReaderDemo.EnumBarcodeFormat = {
Unknown: 234882047,

CODE_39: 1,
CODE_128: 2,
CODE_93: 4,
CODABAR: 8,
ITF: 16,
EAN_13: 32,
EAN_8: 64,
UPC_A: 128,
UPC_E: 256,
INDUSTRIAL_25: 512,
OneD : 1023,

QR_CODE: 67108864,
PDF417: 33554432,
DATAMATRIX: 134217728
};

Dynamsoft.BarcodeReaderDemo.ReadFromURL = function(service, url, format, count, onSuccess, onProgress, onFailure, onAbort)
{
Dynamsoft.BarcodeReaderDemo.ReadInner(service, url, 1, format, count, onSuccess, onProgress, onFailure, onAbort);
};

Dynamsoft.BarcodeReaderDemo.ReadFromImage = function(service, base64img, format, count, onSuccess, onProgress, onFailure, onAbort)
{
Dynamsoft.BarcodeReaderDemo.ReadInner(service, base64img, 0, format, count, onSuccess, onProgress, onFailure, onAbort);
};

Dynamsoft.BarcodeReaderDemo.ReadInner = function(service, urlOrImg, bURL, format, count, onSuccess, onProgress, onFailure, onAbort)
{
var xhr = new XMLHttpRequest();

xhr.addEventListener(“load”, onSuccess, false);
xhr.addEventListener(“error”, onFailure, false);
xhr.addEventListener(“abort”, onAbort, false);
xhr.upload.addEventListener(‘progress’,onProgress, false);

xhr.open(“POST”, service);
xhr.setRequestHeader(‘Content-Type’, ‘application/json’);

var data = “”;

if(bURL)
{
data = JSON.stringify({
“url”: urlOrImg,
“barcodeFormat”: format,
“maxNumPerPage”: count
});
}
else
{
data = JSON.stringify({
“image”: urlOrImg,
“barcodeFormat”: format,
“maxNumPerPage”: count
});
}

xhr.send(data);
};

 

video.js:

/**
* HTML5 Webcam Barcode Reader with Dynamsoft Barcode Reader SDK.
* Support PC.
*/
var videoElement = document.querySelector(‘video’);
var canvas = document.getElementById(‘pcCanvas’);
var videoSelect = document.querySelector(‘select#videoSource’);
var videoOption = document.getElementById(‘videoOption’);
var buttonGo = document.getElementById(‘go’);
var barcode_result = document.getElementById(‘dbr’);

var isPaused = false;
var videoWidth = 640, videoHeight = 640;
var isPC = true;

var seconds = 120;
var countDownId;

// check devices
function browserRedirect() {
var deviceType;
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == “ipad”;
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == “iphone os”;
var bIsMidp = sUserAgent.match(/midp/i) == “midp”;
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == “rv:1.2.3.4”;
var bIsUc = sUserAgent.match(/ucweb/i) == “ucweb”;
var bIsAndroid = sUserAgent.match(/android/i) == “android”;
var bIsCE = sUserAgent.match(/windows ce/i) == “windows ce”;
var bIsWM = sUserAgent.match(/windows mobile/i) == “windows mobile”;
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
deviceType = ‘phone’;
} else {
deviceType = ‘pc’;
}
return deviceType;
}

if (browserRedirect() == ‘pc’) {
isPC = true;
} else {
isPC = true;
}

function countDown() {
buttonGo.textContent = ‘Reading ‘ + ‘(‘ + seconds + ‘ sec)’;
if (seconds > 0) seconds–;
else resetButtonGo();
}

// add button event
buttonGo.onclick = function () {

if (getBarcodeFormat() == 0) {
alert(“Please select barcode types first.”);
return;
}

if (isPC) {
canvas.style.display = ‘none’;
} else {
return;
}

seconds = 120;
countDown();
countDownId = setInterval(countDown, 1000);

isPaused = false;
scanBarcode();
buttonGo.disabled = true;

// clear barcode result
barcode_result.innerHTML = “”;
document.getElementById(“image”).style.display = “none”;
};

$(‘video’).css(‘display’, ‘block’);
$(‘#divErrInfo’).css(‘display’, ‘none’);

// play video
console.log(‘======try getUserMedia========’);
if (!navigator.mediaDevices) {
alert(“Not support `navigator.mediaDevices`.”);
} else {

navigator.mediaDevices.getUserMedia({ video: { facingMode: { exact: ‘environment’ } } }).then((stream) => {
console.log(‘======get video========’);
return new Promise((resolve, reject) => {
var video = $(‘video’)[0];
video.srcObject = stream;
video.onloadedmetadata = () => {
console.log(‘======play video========’);
video.play().then(() => {
console.log(‘======played video========’);
resolve();
}, (ex) => {
reject(ex);
});
};
video.onerror = () => { reject(); };
});
}).catch((ex) => {
console.log(ex);
alert(ex.message || ex);
});
}

// scan barcode
function scanBarcode() {
if (isPaused) {
return;
}

var context = null,
width = 0,
height = 0,
dbrCanvas = null;

if (isPC) {
var ctx = canvas.getContext(‘2d’);
context = ctx;
width = videoWidth;
height = videoHeight;
dbrCanvas = canvas;
} else {
return;
}

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,/, “”);

Dynamsoft.BarcodeReaderDemo.ReadFromImage(“WebcamBarcodeReader.ashx”, data, getBarcodeFormat(), 1, uploadComplete, uploadProgress, uploadFailed, uploadCanceled);
}

function uploadComplete(evt) {
/* This event is raised when the server send back a response */
if (isPaused) {
return;
}
//setTimeout(scanBarcode, 200);
console.log(evt.target.responseText);
var result = JSON.parse(evt.target.responseText);

if (result.barcodes != null && result.barcodes.length > 0) {
//resetButtonGo();

//var strMsg = “Total barcode(s) found: ” + result.barcodes.length + “.<br/>”;
var QRresult = “”;
for (var idx = 0; idx < result.barcodes.length; ++idx) {
//strMsg = strMsg + “Barcode ” + (idx + 1) + “:<br/>”;
//strMsg = strMsg + “Type: <b>” + result.barcodes[idx].formatString + “</b><br/>”;
//strMsg = strMsg + “Value: <b>” + convertTextForHTML(result.barcodes[idx].displayValue) + “</b><br/>”;
QRresult = convertTextForHTML(result.barcodes[idx].displayValue);
//strMsg = strMsg + “<br/>”;
}

var custUserNo = getCookie(‘CustomerUserNo’);
if (custUserNo == null)
window.location = “CustomerSignIn.aspx”;
else
window.location = “CustomerPaymentTrans.aspx”;

function getCookie(cookieName) {
var cookieValue = document.cookie;
var cookieStart = cookieValue.indexOf(” ” + cookieName + “=”);
if (cookieStart == -1) {
cookieStart = cookieValue.indexOf(“=”);
}
if (cookieStart == -1) {
cookieValue = null;
}
else {
cookieStart = cookieValue.indexOf(“=”, cookieStart) + 1;
var cookieEnd = cookieValue.indexOf(“;”, cookieStart);
if (cookieEnd == -1) {
cookieEnd = cookieValue.length;
}
cookieValue = unescape(cookieValue.substring(cookieStart, cookieEnd));
}
return cookieValue;
}

}
else {
setTimeout(scanBarcode, 200);
}
}

function uploadFailed(evt) {
alert(“There was an error attempting to upload the file.”);
}

function uploadCanceled(evt) {
alert(“The upload has been canceled by the user or the browser dropped the connection.”);
}

function uploadProgress(evt) {
}

function ClickCheckBox(obj) {
if (getBarcodeFormat() == 0) {
resetButtonGo();
}
}

function getBarcodeFormat() {
var vType = 0;
var barcodeType = document.getElementsByName(“BarcodeType”);
for (i = 0; i < barcodeType.length; i++) {
if (barcodeType[i].checked == true)
vType = vType | (barcodeType[i].value * 1);
}
return vType;
}

function resetButtonGo() {
isPaused = true;
buttonGo.disabled = false;
buttonGo.textContent = ‘Read Barcode’;
clearInterval(countDownId);
}

function convertTextForHTML(str) {
str = str.replace(/</g, ‘&lt;’);
str = str.replace(/>/g, ‘&gt;’);
str = [‘<pre style=”display:inline;border:none;font-size:inherit;font-family: inherit;background:transparent;white-space:pre-wrap;”>’, str, ‘</pre>’].join(”);
if ((str.indexOf(‘\n’) & str.indexOf(‘\r’)) != -1) {
str = ‘<br>’ + str;
}
return str;
}

 

WebcamBarcodeReader.ashx

using System;
using System.Web;
using System.IO;
using BarcodeDLL;
using Newtonsoft.Json;
using Merchant.BL;
using System.Web.SessionState;

namespace DecodeWebcam
{
/// <summary>
/// Summary description for WebcamBarcodeReader
/// </summary>
public class WebcamBarcodeReader : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
var result = new ReadResult();
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)
{
result.errorCode = (int)Dynamsoft.Barcode.EnumErrorCode.DBRERR_UNKNOWN;
result.errorString = “Post data is null.”;
}
else
{
if (postData.barcodeFormat == 0)
postData.barcodeFormat = 234882047;
if (postData.maxNumPerPage <= 0)
postData.maxNumPerPage = 0x7fffffff;

// 2. reader barcode and output result
BarrecodeReaderRepo.DoBarcode(postData.image, postData.barcodeFormat, postData.maxNumPerPage, ref result);

}

var strResult = JsonConvert.SerializeObject(result);
context.Response.Write(strResult);
if (result.barcodes != null)
{
context.Session.Add(Constants.QRCODE_RESULT, result.barcodes[0].displayValue);
//if (context.Session[Constants.CUSTOMER_BE] == null)
//{
//context.Response.Redirect(“~/CustomerPhoneVerification.aspx”, false);
//context.ApplicationInstance.CompleteRequest();
//}
//else
//context.Response.Redirect(“~/CustomerPaymentTrans.aspx”, false);
}
}
catch (Exception exp)
{
result.errorCode = (int)Dynamsoft.Barcode.EnumErrorCode.DBRERR_UNKNOWN;
result.errorString = exp.Message;

context.Response.Write(JsonConvert.SerializeObject(result));
}
}

public bool IsReusable
{
get
{
return true;
}
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s