Read Barcode From Live Camera - JavaScript
Barcode Reader sample in JavaScript demonstrating ‘Read Barcode From Live Camera’
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Web Barcode Reader
</title>
<link href="Style/index.css" rel="stylesheet" />
</head>
<body>
<div class="upload_camera">
<h1>Barcodes From Camera</h1>
<hr/>
<div id="userMedia" style="display:none; height: 575px; width: 1182px">
<table>
<tr align="left" valign="top">
<td valign="top" colspan="2">
<h5 style=" color:Green; ">(HTML5 based camera) This works in Chrome, Firefox, Safari and other modern browsers with HTML5 support. If HTML5 camera is not enabled then Flash based camera should appear instead. To enable web-cam access answer ALLOW when asked if you want to give access to webcam </h5>
<strong>IMPORTANT: html5 webcam access (Chrome, Firefox, Safari on desktop and iOS) requires SSL connection! Otherwise, web camera will not initialize at all as it requies SSL connection only. </strong>
</td>
</tr>
<tr align="left" valign="top">
<td valign="top">
<br />
<span style=" font-size:20px; ">PDF.co API Key: </span>
<br />
<input type="text" style="width:500px; padding: 5px;" id="txtPDFcoAPIKey" />
<br />
<br />
<span style=" font-size:20px; ">Barcode Types to Read: </span>
<br />
<textarea style="width:500px; height:100px;" size="8" id="txtAreaBarcodeTypes">QRCode,Code39,Code39Extended,Code39Mod43,PDF417</textarea>
<br />
<br />
<span style=" font-size:20px; ">Output barcode values read appears below: </span>
<br />
<!-- decoding results appears in this listbox -->
<textarea style="width:500px; height:100px;" size="8" id="OutListBoxHTML5"></textarea>
<br />
<input id="snap" style="color:black; font-weight:bold; font-size:large;" type="button" onclick="UploadToCloud();" value="START READING BARCODES..." />
<input id="pause" style="color:black;" type="button" onclick="stopCall();" value="STOP" /> <h4 id="report"></h4>
</td>
<td valign="top">
<span>Webcam preview shows below:</span>
<video id="video" width="640" height="480" autoplay playsinline muted></video>
<!-- canvas with the output -->
<canvas id="canvasU" width="640" height="480" style="display:none"></canvas>
</td>
</tr>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="Scripts/webcam.js"></script>
<script type="text/javascript" src="Scripts/index.js"></script>
</body>
</html>
index.js
var canvas, context, timer;
var constraints = window.constraints = {
audio: false,
video: { facingMode: "environment" } // change to "user" for front camera (see https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode )
};
// (HTML5 based camera only) this portion of code will be used when browser supports navigator.getUserMedia ********* */
window.addEventListener("DOMContentLoaded", function () {
canvas = document.getElementById("canvasU"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function (error) {
console.log("Video capture error: ", error.code);
};
// check if we can use HTML5 based camera (through mediaDevices.getUserMedia() function)
if (navigator.mediaDevices.getUserMedia) { // Standard browser
// display HTML5 camera
document.getElementById("userMedia").style.display = '';
// adding click event to take photo from webcam
document.getElementById("snap").addEventListener("click", function () {
context.drawImage(video, 0, 0, 640, 480);
});
navigator.mediaDevices
.getUserMedia(constraints)
.then(handleSuccess)
.catch(handleError);
}
// check if we can use HTML5 based camera (through .getUserMedia() function in Webkit based browser)
else if (navigator.webkitGetUserMedia) { // WebKit-prefixed for Google Chrome
// display HTML5 camera
document.getElementById("userMedia").style.display = '';
// adding click event to take photo from webcam
document.getElementById("snap").addEventListener("click", function () {
context.drawImage(video, 0, 0, 640, 480);
});
navigator.webkitGetUserMedia(videoObj, function (stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
// check if we can use HTML5 based camera (through .getUserMedia() function in Firefox based browser)
else if (navigator.mozGetUserMedia) { // moz-prefixed for Firefox
// display HTML5 camera
document.getElementById("userMedia").style.display = '';
// adding click event to take photo from webcam
document.getElementById("snap").addEventListener("click", function () {
context.drawImage(video, 0, 0, 640, 480);
});
navigator.mozGetUserMedia(videoObj, function (stream) {
video.mozSrcObject = stream;
video.play();
}, errBack);
}
}, false);
function handleSuccess(stream) {
var video = document.querySelector('video');
var videoTracks = stream.getVideoTracks();
console.log('Got stream with constraints:', constraints);
console.log(`Using video device: ${videoTracks[0].label}`);
window.stream = stream; // make variable available to browser console
video.srcObject = stream;
}
function handleError(error) {
if (error.name === 'ConstraintNotSatisfiedError') {
var v = constraints.video;
errorMsg(`The resolution ${v.width.exact}x${v.height.exact} px is not supported by your device.`);
} else if (error.name === 'PermissionDeniedError') {
errorMsg('Permissions have not been granted to use your camera and ' +
'microphone, you need to allow the page access to your devices in ' +
'order for the demo to work.');
}
errorMsg(`getUserMedia error: ${error.name}`, error);
}
function errorMsg(msg, error) {
var errorElement = document.querySelector('#errorMsg');
errorElement.innerHTML += `<p>${msg}</p>`;
if (typeof error !== 'undefined') {
console.error(error);
}
}
// (HTML5 based camera only)
// uploads the image to the server
function UploadToCloud() {
if($.trim($("#txtPDFcoAPIKey").val()) === ""){
alert("PDF.co API Key can not be empty!");
return;
}
if($.trim($("#txtAreaBarcodeTypes").val()) === ""){
alert("PDF.co Barcode Types can not be empty!");
return;
}
$('#report').html("scanning the current frame......");
context.drawImage(video, 0, 0, 640, 480);
var img = canvas.toDataURL('image/jpeg', 0.9);//.split(',')[1];
readBarcodeFromPDF(img);
timer = setTimeout(UploadToCloud, 3000); // will capture new image to detect barcode after 3000 mili second
}
// (flash based camera only) stop the capturing
function stopCall() {
$('#report').html("STOPPED Scanning.");
clearTimeout(timer);
}
function readBarcodeFromPDF(img) {
const PDFcoAPIKey = $("#txtPDFcoAPIKey").val();
const barcodeTypes = $("#txtAreaBarcodeTypes").val();
var form = new FormData();
form.append("file", img);
form.append("name", `Frame_${new Date().getTime()}.jpg`);
var settings_base64Upload = {
"url": "https://api.pdf.co/v1/file/upload/base64",
"method": "POST",
"timeout": 0,
"headers": {
"x-api-key": PDFcoAPIKey
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
// Upload Base64 to PDF.co Cloud
$.ajax(settings_base64Upload).done(function (resp_upload) {
var json_resp_upload = JSON.parse(resp_upload);
var oData_barcodeRead = {
"url": json_resp_upload.url,
"types": barcodeTypes,
"encrypt": false,
"async": false
};
//console.log(oData_barcodeRead);
var settings_barcode_read = {
"url": "https://api.pdf.co/v1/barcode/read/from/url",
"method": "POST",
"timeout": 0,
"headers": {
"x-api-key": PDFcoAPIKey,
"Content-Type": "application/json"
},
"data": JSON.stringify(oData_barcodeRead),
};
$.ajax(settings_barcode_read).done(function (response_barcode) {
if(response_barcode.barcodes && response_barcode.barcodes.length > 0){
for (let i = 0; i < response_barcode.barcodes.length; i++) {
const elmBarcode = response_barcode.barcodes[i];
let htmlSelect = document.getElementById('OutListBoxHTML5');
htmlSelect.value = elmBarcode.Value + "\r\n" + htmlSelect.value;
}
}
});
});
}
webcam.js
��/ / W e b c a m J S v 1 . 0 . 2 5
/ / W e b c a m l i b r a r y f o r c a p t u r i n g J P E G / P N G i m a g e s i n J a v a S c r i p t
/ / A t t e m p t s g e t U s e r M e d i a , f a l l s b a c k t o F l a s h
/ / A u t h o r : J o s e p h H u c k a b y : h t t p : / / g i t h u b . c o m / j h u c k a b y
/ / B a s e d o n J P E G C a m : h t t p : / / c o d e . g o o g l e . c o m / p / j p e g c a m /
/ / C o p y r i g h t ( c ) 2 0 1 2 - 2 0 1 7 J o s e p h H u c k a b y
/ / L i c e n s e d u n d e r t h e M I T L i c e n s e
( f u n c t i o n ( w i n d o w ) {
v a r _ u s e r M e d i a ;
/ / d e c l a r e e r r o r t y p e s
/ / i n h e r i t a n c e p a t t e r n h e r e :
/ / h t t p s : / / s t a c k o v e r f l o w . c o m / q u e s t i o n s / 7 8 3 8 1 8 / h o w - d o - i - c r e a t e - a - c u s t o m - e r r o r - i n - j a v a s c r i p t
f u n c t i o n F l a s h E r r o r ( ) {
v a r t e m p = E r r o r . a p p l y ( t h i s , a r g u m e n t s ) ;
t e m p . n a m e = t h i s . n a m e = " F l a s h E r r o r " ;
t h i s . s t a c k = t e m p . s t a c k ;
t h i s . m e s s a g e = t e m p . m e s s a g e ;
}
f u n c t i o n W e b c a m E r r o r ( ) {
v a r t e m p = E r r o r . a p p l y ( t h i s , a r g u m e n t s ) ;
t e m p . n a m e = t h i s . n a m e = " W e b c a m E r r o r " ;
t h i s . s t a c k = t e m p . s t a c k ;
t h i s . m e s s a g e = t e m p . m e s s a g e ;
}
v a r I n t e r m e d i a t e I n h e r i t o r = f u n c t i o n ( ) { } ;
I n t e r m e d i a t e I n h e r i t o r . p r o t o t y p e = E r r o r . p r o t o t y p e ;
F l a s h E r r o r . p r o t o t y p e = n e w I n t e r m e d i a t e I n h e r i t o r ( ) ;
W e b c a m E r r o r . p r o t o t y p e = n e w I n t e r m e d i a t e I n h e r i t o r ( ) ;
v a r W e b c a m = {
v e r s i o n : ' 1 . 0 . 2 5 ' ,
/ / g l o b a l s
p r o t o c o l : l o c a t i o n . p r o t o c o l . m a t c h ( / h t t p s / i ) ? ' h t t p s ' : ' h t t p ' ,
l o a d e d : f a l s e , / / t r u e w h e n w e b c a m m o v i e f i n i s h e s l o a d i n g
l i v e : f a l s e , / / t r u e w h e n w e b c a m i s i n i t i a l i z e d a n d r e a d y t o s n a p
u s e r M e d i a : t r u e , / / t r u e w h e n g e t U s e r M e d i a i s s u p p o r t e d n a t i v e l y
i O S : / i P a d | i P h o n e | i P o d / . t e s t ( n a v i g a t o r . u s e r A g e n t ) &