Socket
Socket
Sign inDemoInstall

javascript-barcode-reader

Package Overview
Dependencies
90
Maintainers
1
Versions
51
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.6.2 to 0.6.3

dist/lib/src/utilities/adaptiveThreshold.js

685

dist/javascript-barcode-reader.es5.js

@@ -27,31 +27,3 @@ import { read } from 'jimp';

function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var CHAR_SET = {
const CHAR_SET = {
nnnnnww: '0',

@@ -76,11 +48,11 @@ nnnnwwn: '1',

nwnwnnw: 'C',
nnnwwwn: 'D'
nnnwwwn: 'D',
};
function decoder(lines) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return (pre + item) / 2; }, 0));
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => (pre + item) / 2, 0));
// Read one encoded character at a time.
while (lines.length > 0) {
var seg = lines.splice(0, 8).splice(0, 7);
var a = seg.map(function (line) { return (line < barThreshold ? 'n' : 'w'); }).join('');
const seg = lines.splice(0, 8).splice(0, 7);
const a = seg.map(line => (line < barThreshold ? 'n' : 'w')).join('');
code.push(CHAR_SET[a]);

@@ -91,3 +63,3 @@ }

var WIDTH_TBL = [
const WIDTH_TBL = [
'212222',

@@ -201,5 +173,5 @@ '222122',

'211133',
'2331112'
'2331112',
];
var TBL_A = [
const TBL_A = [
' ',

@@ -312,5 +284,5 @@ '!',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var TBL_B = [
const TBL_B = [
' ',

@@ -423,5 +395,5 @@ '!',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var TBL_C = [
const TBL_C = [
'00',

@@ -534,18 +506,24 @@ '01',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var computeGroup = function (lines) {
var factor = lines.reduce(function (pre, item) { return pre + item; }, 0) / (Math.ceil(lines.length / 6) * 11);
// factor = Math.round(factor * 10) / 10
return lines.map(function (item) { return Math.round(item / factor) || 1; });
const computeGroup = (lines) => {
const count = lines.length - 13;
const factor = lines.reduce((pre, item, i) => {
if (i >= count)
return pre;
return pre + item;
}, 0) /
(Math.ceil(count / 6) * 11);
console.log(factor);
return lines.map(item => Math.round(item / factor) || 1);
};
function decoder$1(lines) {
var lookupTBL = TBL_B;
const code = [];
let lookupTBL = TBL_B;
// let sumOP = 0
var letterKey;
var letterCode;
var letterCodePrev;
var keyIndex;
var code = [];
var computedLines = computeGroup(lines);
let letterKey;
let letterCode;
let letterCodePrev;
let keyIndex;
const computedLines = computeGroup(lines);
if (!computedLines)

@@ -555,8 +533,5 @@ return '';

computedLines.pop();
// skip check code and stop code using -12
for (var i = 0; i * 6 < computedLines.length - 12; i += 1) {
// skip check code and stop code using -13
for (let i = 0; i * 6 < computedLines.length - 13; i += 1) {
letterKey = computedLines.slice(i * 6, (i + 1) * 6).join('');
if (letterKey === '114141') {
letterKey = '113141';
}
keyIndex = WIDTH_TBL.indexOf(letterKey);

@@ -595,6 +570,7 @@ letterCode = lookupTBL[keyIndex];

// if (sumOP % 103 !== WIDTH_TBL.indexOf(letterKey)) return ''
console.log('CODE: ', code.join(''));
return code.join('');
}
var CHAR_SET$1 = {
const CHAR_SET$1 = {
nnnwwnwnn: '0',

@@ -643,12 +619,12 @@ wnnwnnnnw: '1',

nnnwnwnwn: '%',
nwnnwnwnn: '*'
nwnnwnwnn: '*',
};
function decoder$2(lines) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return pre + item; }, 0) / lines.length);
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => pre + item, 0) / lines.length);
// Read one encoded character at a time.
while (lines.length > 0) {
var sequenceBar = lines
const sequenceBar = lines
.splice(0, 10)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map(line => (line > barThreshold ? 'w' : 'n'))
.slice(0, 9)

@@ -663,3 +639,3 @@ .join('');

var CHAR_SET$2 = [
const CHAR_SET$2 = [
{ '100010100': '0' },

@@ -712,11 +688,11 @@ { '101001000': '1' },

{ '100110010': '(+)' },
{ '101011110': '*' }
{ '101011110': '*' },
];
function decoder$3(lines) {
var code = [];
var binary = [];
const code = [];
const binary = [];
// remove termination bar
lines.pop();
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return pre + item; }, 0) / lines.length);
var minBarWidth = Math.ceil(lines.reduce(function (pre, item) {
const barThreshold = Math.ceil(lines.reduce((pre, item) => pre + item, 0) / lines.length);
const minBarWidth = Math.ceil(lines.reduce((pre, item) => {
if (item < barThreshold)

@@ -727,4 +703,4 @@ return (pre + item) / 2;

// leave the padded *
for (var i = 0; i < lines.length; i += 1) {
var segment = lines[i];
for (let i = 0; i < lines.length; i += 1) {
let segment = lines[i];
while (segment > 0) {

@@ -740,18 +716,15 @@ if (i % 2 === 0) {

}
var _loop_1 = function (i) {
var searcKey = binary.slice(i, i + 9).join('');
var char = CHAR_SET$2.filter(function (item) { return Object.keys(item)[0] === searcKey; });
for (let i = 0; i < binary.length; i += 9) {
const searcKey = binary.slice(i, i + 9).join('');
const char = CHAR_SET$2.filter(item => Object.keys(item)[0] === searcKey);
code.push(char[0][searcKey]);
};
for (var i = 0; i < binary.length; i += 9) {
_loop_1(i);
}
if (code.shift() !== '*' || code.pop() !== '*')
return '';
var K = code.pop();
var sum = 0;
var letter;
var Value;
var findValue = function (item) { return Object.values(item)[0] === letter; };
for (var i = code.length - 1; i >= 0; i -= 1) {
const K = code.pop();
let sum = 0;
let letter;
let Value;
const findValue = (item) => Object.values(item)[0] === letter;
for (let i = code.length - 1; i >= 0; i -= 1) {
letter = code[i];

@@ -763,5 +736,5 @@ Value = CHAR_SET$2.indexOf(CHAR_SET$2.filter(findValue)[0]);

return '';
var C = code.pop();
const C = code.pop();
sum = 0;
for (var i = code.length - 1; i >= 0; i -= 1) {
for (let i = code.length - 1; i >= 0; i -= 1) {
letter = code[i];

@@ -776,3 +749,3 @@ Value = CHAR_SET$2.indexOf(CHAR_SET$2.filter(findValue)[0]);

var CHAR_SET$3 = [
const CHAR_SET$3 = [
'nnwwn',

@@ -787,16 +760,16 @@ 'wnnnw',

'wnnwn',
'nwnwn'
'nwnwn',
];
function decoder$4(lines, type) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return (pre + item) / 2; }, 0));
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => (pre + item) / 2, 0));
if (type === 'interleaved') {
// extract start/ends pair
var startChar = lines
const startChar = lines
.splice(0, 4)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');
var endChar = lines
const endChar = lines
.splice(lines.length - 3, 3)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -807,11 +780,11 @@ if (startChar !== 'nnnn' || endChar !== 'wnn')

while (lines.length > 0) {
var seg = lines.splice(0, 10);
var a = seg
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
const seg = lines.splice(0, 10);
const a = seg
.filter((item, index) => index % 2 === 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');
code.push(CHAR_SET$3.indexOf(a));
var b = seg
.filter(function (item, index) { return index % 2 !== 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
const b = seg
.filter((item, index) => index % 2 !== 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -823,11 +796,11 @@ code.push(CHAR_SET$3.indexOf(b));

// extract start/ends pair
var startChar = lines
const startChar = lines
.splice(0, 6)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');
var endChar = lines
const endChar = lines
.splice(lines.length - 5, 5)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -838,6 +811,6 @@ if (startChar !== 'wwn' || endChar !== 'wnw')

while (lines.length > 0) {
var a = lines
const a = lines
.splice(0, 10)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -850,3 +823,3 @@ code.push(CHAR_SET$3.indexOf(a));

var UPC_SET = {
const UPC_SET = {
'3211': '0',

@@ -861,8 +834,8 @@ '2221': '1',

'1213': '8',
'3112': '9'
'3112': '9',
};
function decoder$5(lines) {
var code = '';
let code = '';
// start indicator/reference lines
var bar = (lines[0] + lines[1] + lines[2]) / 3;
const bar = (lines[0] + lines[1] + lines[2]) / 3;
// remove start pattern

@@ -878,8 +851,6 @@ lines.shift();

lines.splice(24, 5);
for (var i = 0; i < lines.length; i += 4) {
var group = lines.slice(i, i + 4);
var digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(function (digit) {
return digit === 1.5 ? 1 : Math.round(digit);
});
var result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
for (let i = 0; i < lines.length; i += 4) {
const group = lines.slice(i, i + 4);
const digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(digit => digit === 1.5 ? 1 : Math.round(digit));
const result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
if (result) {

@@ -895,3 +866,3 @@ code += result;

var UPC_SET$1 = {
const UPC_SET$1 = {
'3211': '0',

@@ -906,8 +877,8 @@ '2221': '1',

'1213': '8',
'3112': '9'
'3112': '9',
};
function decoder$6(lines) {
var code = '';
let code = '';
// start indicator/reference lines
var bar = (lines[0] + lines[1] + lines[2]) / 3;
const bar = (lines[0] + lines[1] + lines[2]) / 3;
// remove start pattern

@@ -923,8 +894,6 @@ lines.shift();

lines.splice(16, 5);
for (var i = 0; i < lines.length; i += 4) {
var group = lines.slice(i, i + 4);
var digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(function (digit) {
return digit === 1.5 ? 1 : Math.round(digit);
});
var result = UPC_SET$1[digits.join('')] || UPC_SET$1[digits.reverse().join('')];
for (let i = 0; i < lines.length; i += 4) {
const group = lines.slice(i, i + 4);
const digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(digit => digit === 1.5 ? 1 : Math.round(digit));
const result = UPC_SET$1[digits.join('')] || UPC_SET$1[digits.reverse().join('')];
if (result) {

@@ -940,2 +909,62 @@ code += result;

function applyAdaptiveThreshold(data, width, height) {
const integralImage = new Array(width * height).fill(0);
const channels = data.length / (width * height);
const t = 0.15; // threshold percentage
const s = Math.floor(height); // bracket size
const s2 = Math.floor(s / 2);
for (let i = 0; i < width; i += 1) {
let sum = 0;
for (let j = 0; j < height; j += 1) {
const pureIndex = j * width + i;
const index = pureIndex * channels;
// greyscale
const v = (data[index] + data[index + 1] + data[index + 2]) / 3;
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
sum += v;
if (i === 0) {
integralImage[pureIndex] = sum;
}
else {
integralImage[pureIndex] = integralImage[pureIndex - 1] + sum;
}
}
}
// skip edge rows
for (let i = 0; i < width; i += 1) {
for (let j = 0; j < height; j += 1) {
const pureIndex = j * width + i;
const index = pureIndex * channels;
// no. of pixels per window
let x1 = i - s2;
let x2 = i + s2;
let y1 = j - s2;
let y2 = j + s2;
if (x1 < 0)
x1 = 0;
if (x2 >= width)
x2 = width - 1;
if (y1 < 0)
y1 = 0;
if (y2 >= height)
y2 = height - 1;
const count = (x2 - x1) * (y2 - y1);
const sum = integralImage[y2 * width + x2] -
integralImage[y1 * width + x2] -
integralImage[y2 * width + x1] +
integralImage[y1 * width + x1];
let v = 255;
if (data[index] * count < sum * (1 - t)) {
v = 0;
}
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
}
}
return data;
}
function combineAllPossible(finalResult, result) {

@@ -945,5 +974,5 @@ if (finalResult === '' || result === '') {

}
var finalResultArr = finalResult.split('');
var resultArr = result.split('');
resultArr.forEach(function (char, index) {
const finalResultArr = finalResult.split('');
const resultArr = result.split('');
resultArr.forEach((char, index) => {
if (!finalResultArr[index] || finalResultArr[index] === '?') {

@@ -959,8 +988,8 @@ if (char && char !== '?') {

function createImageData(image) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx)
throw new Error('canvas not available');
var width = image.naturalWidth;
var height = image.naturalHeight;
const width = image.naturalWidth;
const height = image.naturalHeight;
canvas.width = width;

@@ -973,3 +1002,3 @@ canvas.height = height;

function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
if (s.startsWith('#'))

@@ -980,53 +1009,51 @@ return false;

var isNode = typeof process === 'object' && process.release && process.release.name === 'node';
const isNode = typeof process === 'object' && process.release && process.release.name === 'node';
function getImageDataFromSource(source) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
if (typeof source === 'string') {
if (source.startsWith('#')) {
var imageElement = document.getElementById(source.substr(1));
if (imageElement instanceof HTMLImageElement) {
resolve(createImageData(imageElement));
}
if (imageElement instanceof HTMLCanvasElement) {
var ctx = imageElement.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, imageElement.width, imageElement.height));
}
reject(new Error('Invalid image source specified!'));
}
else if (isUrl(source)) {
var img_1 = new Image();
img_1.onerror = reject;
img_1.onload = function () { return resolve(createImageData(img_1)); };
img_1.src = source;
}
else if (isNode) {
read(source, function (err, image) {
if (err) {
reject(err);
}
else {
var _a = image.bitmap, data = _a.data, width = _a.width, height = _a.height;
resolve({
data: Uint8ClampedArray.from(data),
width: width,
height: height
});
}
});
}
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (typeof source === 'string') {
if (source.startsWith('#')) {
const imageElement = document.getElementById(source.substr(1));
if (imageElement instanceof HTMLImageElement) {
resolve(createImageData(imageElement));
}
else if (source instanceof HTMLImageElement) {
resolve(createImageData(source));
}
else if (source instanceof HTMLCanvasElement) {
var ctx = source.getContext('2d');
if (imageElement instanceof HTMLCanvasElement) {
const ctx = imageElement.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, source.width, source.height));
resolve(ctx.getImageData(0, 0, imageElement.width, imageElement.height));
}
})];
reject(new Error('Invalid image source specified!'));
}
else if (isUrl(source)) {
const img = new Image();
img.onerror = reject;
img.onload = () => resolve(createImageData(img));
img.src = source;
}
else if (isNode) {
read(source, (err, image) => {
if (err) {
reject(err);
}
else {
const { data, width, height } = image.bitmap;
resolve({
data: Uint8ClampedArray.from(data),
width,
height,
});
}
});
}
}
else if (source instanceof HTMLImageElement) {
resolve(createImageData(source));
}
else if (source instanceof HTMLCanvasElement) {
const ctx = source.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, source.width, source.height));
}
});

@@ -1036,21 +1063,53 @@ });

function applyMedianFilter(data, width, height, windowSize = 3) {
const channels = data.length / (width * height);
const filterWindow = [];
const limit = (windowSize - 1) / 2;
for (let i = limit * -1; i < limit + 1; i += 1) {
for (let j = limit * -1; j < limit + 1; j += 1) {
filterWindow.push([i, j]);
}
}
for (let col = limit; col < width - limit; col += 1) {
for (let row = limit; row < height - limit; row += 1) {
const index = (row * width + col) * channels;
const arr = [];
for (let z = 0; z < filterWindow.length; z += 1) {
const i = ((row + filterWindow[z][0]) * width + (col + filterWindow[z][1])) * channels;
const average = Math.sqrt((Math.pow(data[i], 2) + Math.pow(data[i + 1], 2) + Math.pow(data[i + 2], 2)) / 3);
arr.push(average);
}
const sorted = arr.sort((a, b) => a - b);
const medianValue = sorted[Math.floor(sorted.length / 2)];
// const thresholdValue = medianValue >= 180 ? 255 : 0
data[index + 0] = medianValue;
data[index + 1] = medianValue;
data[index + 2] = medianValue;
if (channels === 4)
data[index + 3] = 255;
}
}
return data;
}
function getLines(data, width, height) {
var channels = data.length / (width * height);
var lines = [];
var count = 0;
var colSum = 0;
var colAvg = 0;
var colAvgLast = 0;
for (var col = 0; col < width; col += 1) {
colSum = 0;
for (var row = 0; row < height; row += 1) {
colSum += data[(row * width + col) * channels];
const dataSlice = applyMedianFilter(data, width, height);
const channels = dataSlice.length / (width * height);
const lines = [];
let count = 0;
let columnAverageLast = 0;
for (let column = 0; column < width; column += 1) {
let columnSum = 0;
let columnAverage = 0;
for (let row = 0; row < height; row += 1) {
const index = (row * width + column) * channels;
columnSum += Math.sqrt((Math.pow(data[index], 2) + Math.pow(data[index + 1], 2) + Math.pow(data[index + 2], 2)) / 3);
}
// atleast 75% of the pixels are same in column
colAvg = colSum / height >= 127 ? 255 : 0;
// skip white padding in the start
if (count === 0 && colAvg === 255)
// pixels are same in column
columnAverage = columnSum / height >= 127 ? 255 : 0;
// skip white padding in the start & end
if (columnAverage === 255 && count === 0)
continue;
// count line width
if (colAvg === colAvgLast) {
if (columnAverage === columnAverageLast) {
count += 1;

@@ -1060,7 +1119,7 @@ }

lines.push(count);
columnAverageLast = columnAverage;
count = 1;
colAvgLast = colAvg;
}
// skip padding in the last
if (col === width - 1 && colAvg === 0) {
if (column === width - 1 && columnAverage === 0) {
lines.push(count);

@@ -1072,78 +1131,3 @@ }

function applyAdaptiveThreshold(data, width, height) {
var integralImage = new Array(width * height).fill(0);
var channels = data.length / (width * height);
var t = 0.15; // threshold percentage
var s = Math.floor(width / 4); // bracket size
var s2 = Math.ceil(s / 2);
for (var i = 0; i < width; i += 1) {
var sum = 0;
for (var j = 0; j < height; j += 1) {
var pureIndex = j * width + i;
var index = pureIndex * channels;
// greyscale
var v = (data[index] + data[index + 1] + data[index + 2]) / 3;
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
sum += v;
if (i === 0) {
integralImage[pureIndex] = sum;
}
else {
integralImage[pureIndex] = integralImage[pureIndex - 1] + sum;
}
}
}
// skip edge rows
for (var i = 0; i < width; i += 1) {
for (var j = 0; j < height; j += 1) {
var pureIndex = j * width + i;
var index = pureIndex * channels;
// no. of pixels per window
var x1 = i - s2;
var x2 = i + s2;
var y1 = j - s2;
var y2 = j + s2;
if (x1 < 0)
x1 = 0;
if (x2 >= width)
x2 = width - 1;
if (y1 < 0)
y1 = 0;
if (y2 >= height)
y2 = height - 1;
var count = (x2 - x1) * (y2 - y1);
var sum = integralImage[y2 * width + x2] -
integralImage[y1 * width + x2] -
integralImage[y2 * width + x1] +
integralImage[y1 * width + x1];
var v = 255;
if (data[index] * count < sum * (1 - t)) {
v = 0;
}
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
}
}
return data;
}
function applySimpleThreshold(data, width, height) {
var channels = data.length / (width * height);
for (var i = 0; i < data.length; i += channels) {
var r = data[i];
var g = data[i + 1];
var b = data[i + 2];
var v = (r + g + b) / 3;
v = v >= 127 ? 255 : 0;
data[i] = v;
data[i + 1] = v;
data[i + 2] = v;
}
return data;
}
var isTestEnv = process && process.env.NODE_ENV === 'test';
const isTestEnv = process && process.env.NODE_ENV === 'test';
var BARCODE_DECODERS;

@@ -1162,86 +1146,69 @@ (function (BARCODE_DECODERS) {

}
function javascriptBarcodeReader(_a) {
var image = _a.image, barcode = _a.barcode, barcodeType = _a.barcodeType, options = _a.options;
return __awaiter(this, void 0, void 0, function () {
var decoder$7, useSinglePass, imageData, _b, width, height, data, channels, finalResult, sPoints, slineStep, rowsToScan, i, sPoint, start, end, dataSlice, lines, result;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
switch (barcode) {
case BARCODE_DECODERS.codabar:
decoder$7 = decoder;
break;
case BARCODE_DECODERS['code-128']:
decoder$7 = decoder$1;
break;
case BARCODE_DECODERS['code-39']:
decoder$7 = decoder$2;
break;
case BARCODE_DECODERS['code-93']:
decoder$7 = decoder$3;
break;
case BARCODE_DECODERS['code-2of5']:
decoder$7 = decoder$4;
break;
case BARCODE_DECODERS['ean-13']:
decoder$7 = decoder$5;
break;
case BARCODE_DECODERS['ean-8']:
decoder$7 = decoder$6;
break;
default:
throw new Error("Invalid barcode specified. Available decoders: " + BARCODE_DECODERS + ".");
}
useSinglePass = isTestEnv || (options && options.singlePass) || false;
if (!isImageLike(image)) return [3 /*break*/, 1];
_b = image;
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, getImageDataFromSource(image)];
case 2:
_b = _c.sent();
_c.label = 3;
case 3:
imageData = _b;
width = imageData.width;
height = imageData.height;
data = imageData.data;
channels = data.length / (width * height);
finalResult = '';
// apply adaptive threshold
if (options && options.useAdaptiveThreshold) {
data = applyAdaptiveThreshold(data, width, height);
}
sPoints = [5, 6, 4, 7, 3, 8, 2, 9, 1];
slineStep = Math.round(height / sPoints.length);
rowsToScan = Math.min(5, height);
for (i = 0; i < sPoints.length; i += 1) {
sPoint = sPoints[i];
start = channels * width * Math.floor(slineStep * sPoint);
end = start + rowsToScan * channels * width;
dataSlice = data.slice(start, end);
if (!options || !options.useAdaptiveThreshold) {
dataSlice = applySimpleThreshold(dataSlice, width, height);
}
lines = getLines(dataSlice, width, rowsToScan);
if (lines.length === 0) {
if (useSinglePass)
throw new Error('Failed to extract barcode!');
continue;
}
result = decoder$7(lines, barcodeType);
if (useSinglePass)
return [2 /*return*/, result];
if (!result)
continue;
if (!result.includes('?'))
return [2 /*return*/, result];
finalResult = combineAllPossible(finalResult, result);
if (!finalResult.includes('?'))
return [2 /*return*/, finalResult];
if (i === sPoints.length - 1)
return [2 /*return*/, finalResult];
}
function javascriptBarcodeReader({ image, barcode, barcodeType, options, }) {
return __awaiter(this, void 0, void 0, function* () {
let decoder$7;
switch (barcode) {
case BARCODE_DECODERS.codabar:
decoder$7 = decoder;
break;
case BARCODE_DECODERS['code-128']:
decoder$7 = decoder$1;
break;
case BARCODE_DECODERS['code-39']:
decoder$7 = decoder$2;
break;
case BARCODE_DECODERS['code-93']:
decoder$7 = decoder$3;
break;
case BARCODE_DECODERS['code-2of5']:
decoder$7 = decoder$4;
break;
case BARCODE_DECODERS['ean-13']:
decoder$7 = decoder$5;
break;
case BARCODE_DECODERS['ean-8']:
decoder$7 = decoder$6;
break;
default:
throw new Error(`Invalid barcode specified. Available decoders: ${BARCODE_DECODERS}.`);
}
const useSinglePass = isTestEnv || (options && options.singlePass) || false;
const imageData = isImageLike(image) ? image : yield getImageDataFromSource(image);
const width = imageData.width;
const height = imageData.height;
const channels = imageData.data.length / (width * height);
let finalResult = '';
// apply adaptive threshold
if (options && options.useAdaptiveThreshold) {
applyAdaptiveThreshold(imageData.data, width, height);
}
// check points for barcode location
const sPoints = [5, 6, 4, 7, 3, 8, 2, 9, 1];
const slineStep = Math.round(height / sPoints.length);
const rowsToScan = Math.min(3, height);
for (let i = 0; i < sPoints.length; i += 1) {
const sPoint = sPoints[i];
const start = channels * width * Math.floor(slineStep * sPoint);
const end = start + rowsToScan * channels * width;
const lines = getLines(imageData.data.slice(start, end), width, rowsToScan);
if (lines.length === 0) {
if (useSinglePass)
throw new Error('Failed to extract barcode!');
continue;
}
});
// Run the decoder
const result = decoder$7(lines, barcodeType);
if (useSinglePass)
return result;
if (!result)
continue;
if (!result.includes('?'))
return result;
finalResult = combineAllPossible(finalResult, result);
if (!finalResult.includes('?'))
return finalResult;
if (i === sPoints.length - 1)
return finalResult;
}
throw new Error('Failed to extract barcode!');
});

@@ -1248,0 +1215,0 @@ }

@@ -31,31 +31,3 @@ (function (global, factory) {

function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var CHAR_SET = {
const CHAR_SET = {
nnnnnww: '0',

@@ -80,11 +52,11 @@ nnnnwwn: '1',

nwnwnnw: 'C',
nnnwwwn: 'D'
nnnwwwn: 'D',
};
function decoder(lines) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return (pre + item) / 2; }, 0));
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => (pre + item) / 2, 0));
// Read one encoded character at a time.
while (lines.length > 0) {
var seg = lines.splice(0, 8).splice(0, 7);
var a = seg.map(function (line) { return (line < barThreshold ? 'n' : 'w'); }).join('');
const seg = lines.splice(0, 8).splice(0, 7);
const a = seg.map(line => (line < barThreshold ? 'n' : 'w')).join('');
code.push(CHAR_SET[a]);

@@ -95,3 +67,3 @@ }

var WIDTH_TBL = [
const WIDTH_TBL = [
'212222',

@@ -205,5 +177,5 @@ '222122',

'211133',
'2331112'
'2331112',
];
var TBL_A = [
const TBL_A = [
' ',

@@ -316,5 +288,5 @@ '!',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var TBL_B = [
const TBL_B = [
' ',

@@ -427,5 +399,5 @@ '!',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var TBL_C = [
const TBL_C = [
'00',

@@ -538,18 +510,24 @@ '01',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var computeGroup = function (lines) {
var factor = lines.reduce(function (pre, item) { return pre + item; }, 0) / (Math.ceil(lines.length / 6) * 11);
// factor = Math.round(factor * 10) / 10
return lines.map(function (item) { return Math.round(item / factor) || 1; });
const computeGroup = (lines) => {
const count = lines.length - 13;
const factor = lines.reduce((pre, item, i) => {
if (i >= count)
return pre;
return pre + item;
}, 0) /
(Math.ceil(count / 6) * 11);
console.log(factor);
return lines.map(item => Math.round(item / factor) || 1);
};
function decoder$1(lines) {
var lookupTBL = TBL_B;
const code = [];
let lookupTBL = TBL_B;
// let sumOP = 0
var letterKey;
var letterCode;
var letterCodePrev;
var keyIndex;
var code = [];
var computedLines = computeGroup(lines);
let letterKey;
let letterCode;
let letterCodePrev;
let keyIndex;
const computedLines = computeGroup(lines);
if (!computedLines)

@@ -559,8 +537,5 @@ return '';

computedLines.pop();
// skip check code and stop code using -12
for (var i = 0; i * 6 < computedLines.length - 12; i += 1) {
// skip check code and stop code using -13
for (let i = 0; i * 6 < computedLines.length - 13; i += 1) {
letterKey = computedLines.slice(i * 6, (i + 1) * 6).join('');
if (letterKey === '114141') {
letterKey = '113141';
}
keyIndex = WIDTH_TBL.indexOf(letterKey);

@@ -599,6 +574,7 @@ letterCode = lookupTBL[keyIndex];

// if (sumOP % 103 !== WIDTH_TBL.indexOf(letterKey)) return ''
console.log('CODE: ', code.join(''));
return code.join('');
}
var CHAR_SET$1 = {
const CHAR_SET$1 = {
nnnwwnwnn: '0',

@@ -647,12 +623,12 @@ wnnwnnnnw: '1',

nnnwnwnwn: '%',
nwnnwnwnn: '*'
nwnnwnwnn: '*',
};
function decoder$2(lines) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return pre + item; }, 0) / lines.length);
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => pre + item, 0) / lines.length);
// Read one encoded character at a time.
while (lines.length > 0) {
var sequenceBar = lines
const sequenceBar = lines
.splice(0, 10)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map(line => (line > barThreshold ? 'w' : 'n'))
.slice(0, 9)

@@ -667,3 +643,3 @@ .join('');

var CHAR_SET$2 = [
const CHAR_SET$2 = [
{ '100010100': '0' },

@@ -716,11 +692,11 @@ { '101001000': '1' },

{ '100110010': '(+)' },
{ '101011110': '*' }
{ '101011110': '*' },
];
function decoder$3(lines) {
var code = [];
var binary = [];
const code = [];
const binary = [];
// remove termination bar
lines.pop();
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return pre + item; }, 0) / lines.length);
var minBarWidth = Math.ceil(lines.reduce(function (pre, item) {
const barThreshold = Math.ceil(lines.reduce((pre, item) => pre + item, 0) / lines.length);
const minBarWidth = Math.ceil(lines.reduce((pre, item) => {
if (item < barThreshold)

@@ -731,4 +707,4 @@ return (pre + item) / 2;

// leave the padded *
for (var i = 0; i < lines.length; i += 1) {
var segment = lines[i];
for (let i = 0; i < lines.length; i += 1) {
let segment = lines[i];
while (segment > 0) {

@@ -744,18 +720,15 @@ if (i % 2 === 0) {

}
var _loop_1 = function (i) {
var searcKey = binary.slice(i, i + 9).join('');
var char = CHAR_SET$2.filter(function (item) { return Object.keys(item)[0] === searcKey; });
for (let i = 0; i < binary.length; i += 9) {
const searcKey = binary.slice(i, i + 9).join('');
const char = CHAR_SET$2.filter(item => Object.keys(item)[0] === searcKey);
code.push(char[0][searcKey]);
};
for (var i = 0; i < binary.length; i += 9) {
_loop_1(i);
}
if (code.shift() !== '*' || code.pop() !== '*')
return '';
var K = code.pop();
var sum = 0;
var letter;
var Value;
var findValue = function (item) { return Object.values(item)[0] === letter; };
for (var i = code.length - 1; i >= 0; i -= 1) {
const K = code.pop();
let sum = 0;
let letter;
let Value;
const findValue = (item) => Object.values(item)[0] === letter;
for (let i = code.length - 1; i >= 0; i -= 1) {
letter = code[i];

@@ -767,5 +740,5 @@ Value = CHAR_SET$2.indexOf(CHAR_SET$2.filter(findValue)[0]);

return '';
var C = code.pop();
const C = code.pop();
sum = 0;
for (var i = code.length - 1; i >= 0; i -= 1) {
for (let i = code.length - 1; i >= 0; i -= 1) {
letter = code[i];

@@ -780,3 +753,3 @@ Value = CHAR_SET$2.indexOf(CHAR_SET$2.filter(findValue)[0]);

var CHAR_SET$3 = [
const CHAR_SET$3 = [
'nnwwn',

@@ -791,16 +764,16 @@ 'wnnnw',

'wnnwn',
'nwnwn'
'nwnwn',
];
function decoder$4(lines, type) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return (pre + item) / 2; }, 0));
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => (pre + item) / 2, 0));
if (type === 'interleaved') {
// extract start/ends pair
var startChar = lines
const startChar = lines
.splice(0, 4)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');
var endChar = lines
const endChar = lines
.splice(lines.length - 3, 3)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -811,11 +784,11 @@ if (startChar !== 'nnnn' || endChar !== 'wnn')

while (lines.length > 0) {
var seg = lines.splice(0, 10);
var a = seg
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
const seg = lines.splice(0, 10);
const a = seg
.filter((item, index) => index % 2 === 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');
code.push(CHAR_SET$3.indexOf(a));
var b = seg
.filter(function (item, index) { return index % 2 !== 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
const b = seg
.filter((item, index) => index % 2 !== 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -827,11 +800,11 @@ code.push(CHAR_SET$3.indexOf(b));

// extract start/ends pair
var startChar = lines
const startChar = lines
.splice(0, 6)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');
var endChar = lines
const endChar = lines
.splice(lines.length - 5, 5)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -842,6 +815,6 @@ if (startChar !== 'wwn' || endChar !== 'wnw')

while (lines.length > 0) {
var a = lines
const a = lines
.splice(0, 10)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -854,3 +827,3 @@ code.push(CHAR_SET$3.indexOf(a));

var UPC_SET = {
const UPC_SET = {
'3211': '0',

@@ -865,8 +838,8 @@ '2221': '1',

'1213': '8',
'3112': '9'
'3112': '9',
};
function decoder$5(lines) {
var code = '';
let code = '';
// start indicator/reference lines
var bar = (lines[0] + lines[1] + lines[2]) / 3;
const bar = (lines[0] + lines[1] + lines[2]) / 3;
// remove start pattern

@@ -882,8 +855,6 @@ lines.shift();

lines.splice(24, 5);
for (var i = 0; i < lines.length; i += 4) {
var group = lines.slice(i, i + 4);
var digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(function (digit) {
return digit === 1.5 ? 1 : Math.round(digit);
});
var result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
for (let i = 0; i < lines.length; i += 4) {
const group = lines.slice(i, i + 4);
const digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(digit => digit === 1.5 ? 1 : Math.round(digit));
const result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
if (result) {

@@ -899,3 +870,3 @@ code += result;

var UPC_SET$1 = {
const UPC_SET$1 = {
'3211': '0',

@@ -910,8 +881,8 @@ '2221': '1',

'1213': '8',
'3112': '9'
'3112': '9',
};
function decoder$6(lines) {
var code = '';
let code = '';
// start indicator/reference lines
var bar = (lines[0] + lines[1] + lines[2]) / 3;
const bar = (lines[0] + lines[1] + lines[2]) / 3;
// remove start pattern

@@ -927,8 +898,6 @@ lines.shift();

lines.splice(16, 5);
for (var i = 0; i < lines.length; i += 4) {
var group = lines.slice(i, i + 4);
var digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(function (digit) {
return digit === 1.5 ? 1 : Math.round(digit);
});
var result = UPC_SET$1[digits.join('')] || UPC_SET$1[digits.reverse().join('')];
for (let i = 0; i < lines.length; i += 4) {
const group = lines.slice(i, i + 4);
const digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(digit => digit === 1.5 ? 1 : Math.round(digit));
const result = UPC_SET$1[digits.join('')] || UPC_SET$1[digits.reverse().join('')];
if (result) {

@@ -944,2 +913,62 @@ code += result;

function applyAdaptiveThreshold(data, width, height) {
const integralImage = new Array(width * height).fill(0);
const channels = data.length / (width * height);
const t = 0.15; // threshold percentage
const s = Math.floor(height); // bracket size
const s2 = Math.floor(s / 2);
for (let i = 0; i < width; i += 1) {
let sum = 0;
for (let j = 0; j < height; j += 1) {
const pureIndex = j * width + i;
const index = pureIndex * channels;
// greyscale
const v = (data[index] + data[index + 1] + data[index + 2]) / 3;
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
sum += v;
if (i === 0) {
integralImage[pureIndex] = sum;
}
else {
integralImage[pureIndex] = integralImage[pureIndex - 1] + sum;
}
}
}
// skip edge rows
for (let i = 0; i < width; i += 1) {
for (let j = 0; j < height; j += 1) {
const pureIndex = j * width + i;
const index = pureIndex * channels;
// no. of pixels per window
let x1 = i - s2;
let x2 = i + s2;
let y1 = j - s2;
let y2 = j + s2;
if (x1 < 0)
x1 = 0;
if (x2 >= width)
x2 = width - 1;
if (y1 < 0)
y1 = 0;
if (y2 >= height)
y2 = height - 1;
const count = (x2 - x1) * (y2 - y1);
const sum = integralImage[y2 * width + x2] -
integralImage[y1 * width + x2] -
integralImage[y2 * width + x1] +
integralImage[y1 * width + x1];
let v = 255;
if (data[index] * count < sum * (1 - t)) {
v = 0;
}
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
}
}
return data;
}
function combineAllPossible(finalResult, result) {

@@ -949,5 +978,5 @@ if (finalResult === '' || result === '') {

}
var finalResultArr = finalResult.split('');
var resultArr = result.split('');
resultArr.forEach(function (char, index) {
const finalResultArr = finalResult.split('');
const resultArr = result.split('');
resultArr.forEach((char, index) => {
if (!finalResultArr[index] || finalResultArr[index] === '?') {

@@ -963,8 +992,8 @@ if (char && char !== '?') {

function createImageData(image) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx)
throw new Error('canvas not available');
var width = image.naturalWidth;
var height = image.naturalHeight;
const width = image.naturalWidth;
const height = image.naturalHeight;
canvas.width = width;

@@ -977,3 +1006,3 @@ canvas.height = height;

function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
if (s.startsWith('#'))

@@ -984,53 +1013,51 @@ return false;

var isNode = typeof process === 'object' && process.release && process.release.name === 'node';
const isNode = typeof process === 'object' && process.release && process.release.name === 'node';
function getImageDataFromSource(source) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
if (typeof source === 'string') {
if (source.startsWith('#')) {
var imageElement = document.getElementById(source.substr(1));
if (imageElement instanceof HTMLImageElement) {
resolve(createImageData(imageElement));
}
if (imageElement instanceof HTMLCanvasElement) {
var ctx = imageElement.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, imageElement.width, imageElement.height));
}
reject(new Error('Invalid image source specified!'));
}
else if (isUrl(source)) {
var img_1 = new Image();
img_1.onerror = reject;
img_1.onload = function () { return resolve(createImageData(img_1)); };
img_1.src = source;
}
else if (isNode) {
Jimp.read(source, function (err, image) {
if (err) {
reject(err);
}
else {
var _a = image.bitmap, data = _a.data, width = _a.width, height = _a.height;
resolve({
data: Uint8ClampedArray.from(data),
width: width,
height: height
});
}
});
}
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (typeof source === 'string') {
if (source.startsWith('#')) {
const imageElement = document.getElementById(source.substr(1));
if (imageElement instanceof HTMLImageElement) {
resolve(createImageData(imageElement));
}
else if (source instanceof HTMLImageElement) {
resolve(createImageData(source));
}
else if (source instanceof HTMLCanvasElement) {
var ctx = source.getContext('2d');
if (imageElement instanceof HTMLCanvasElement) {
const ctx = imageElement.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, source.width, source.height));
resolve(ctx.getImageData(0, 0, imageElement.width, imageElement.height));
}
})];
reject(new Error('Invalid image source specified!'));
}
else if (isUrl(source)) {
const img = new Image();
img.onerror = reject;
img.onload = () => resolve(createImageData(img));
img.src = source;
}
else if (isNode) {
Jimp.read(source, (err, image) => {
if (err) {
reject(err);
}
else {
const { data, width, height } = image.bitmap;
resolve({
data: Uint8ClampedArray.from(data),
width,
height,
});
}
});
}
}
else if (source instanceof HTMLImageElement) {
resolve(createImageData(source));
}
else if (source instanceof HTMLCanvasElement) {
const ctx = source.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, source.width, source.height));
}
});

@@ -1040,21 +1067,53 @@ });

function applyMedianFilter(data, width, height, windowSize = 3) {
const channels = data.length / (width * height);
const filterWindow = [];
const limit = (windowSize - 1) / 2;
for (let i = limit * -1; i < limit + 1; i += 1) {
for (let j = limit * -1; j < limit + 1; j += 1) {
filterWindow.push([i, j]);
}
}
for (let col = limit; col < width - limit; col += 1) {
for (let row = limit; row < height - limit; row += 1) {
const index = (row * width + col) * channels;
const arr = [];
for (let z = 0; z < filterWindow.length; z += 1) {
const i = ((row + filterWindow[z][0]) * width + (col + filterWindow[z][1])) * channels;
const average = Math.sqrt((Math.pow(data[i], 2) + Math.pow(data[i + 1], 2) + Math.pow(data[i + 2], 2)) / 3);
arr.push(average);
}
const sorted = arr.sort((a, b) => a - b);
const medianValue = sorted[Math.floor(sorted.length / 2)];
// const thresholdValue = medianValue >= 180 ? 255 : 0
data[index + 0] = medianValue;
data[index + 1] = medianValue;
data[index + 2] = medianValue;
if (channels === 4)
data[index + 3] = 255;
}
}
return data;
}
function getLines(data, width, height) {
var channels = data.length / (width * height);
var lines = [];
var count = 0;
var colSum = 0;
var colAvg = 0;
var colAvgLast = 0;
for (var col = 0; col < width; col += 1) {
colSum = 0;
for (var row = 0; row < height; row += 1) {
colSum += data[(row * width + col) * channels];
const dataSlice = applyMedianFilter(data, width, height);
const channels = dataSlice.length / (width * height);
const lines = [];
let count = 0;
let columnAverageLast = 0;
for (let column = 0; column < width; column += 1) {
let columnSum = 0;
let columnAverage = 0;
for (let row = 0; row < height; row += 1) {
const index = (row * width + column) * channels;
columnSum += Math.sqrt((Math.pow(data[index], 2) + Math.pow(data[index + 1], 2) + Math.pow(data[index + 2], 2)) / 3);
}
// atleast 75% of the pixels are same in column
colAvg = colSum / height >= 127 ? 255 : 0;
// skip white padding in the start
if (count === 0 && colAvg === 255)
// pixels are same in column
columnAverage = columnSum / height >= 127 ? 255 : 0;
// skip white padding in the start & end
if (columnAverage === 255 && count === 0)
continue;
// count line width
if (colAvg === colAvgLast) {
if (columnAverage === columnAverageLast) {
count += 1;

@@ -1064,7 +1123,7 @@ }

lines.push(count);
columnAverageLast = columnAverage;
count = 1;
colAvgLast = colAvg;
}
// skip padding in the last
if (col === width - 1 && colAvg === 0) {
if (column === width - 1 && columnAverage === 0) {
lines.push(count);

@@ -1076,78 +1135,3 @@ }

function applyAdaptiveThreshold(data, width, height) {
var integralImage = new Array(width * height).fill(0);
var channels = data.length / (width * height);
var t = 0.15; // threshold percentage
var s = Math.floor(width / 4); // bracket size
var s2 = Math.ceil(s / 2);
for (var i = 0; i < width; i += 1) {
var sum = 0;
for (var j = 0; j < height; j += 1) {
var pureIndex = j * width + i;
var index = pureIndex * channels;
// greyscale
var v = (data[index] + data[index + 1] + data[index + 2]) / 3;
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
sum += v;
if (i === 0) {
integralImage[pureIndex] = sum;
}
else {
integralImage[pureIndex] = integralImage[pureIndex - 1] + sum;
}
}
}
// skip edge rows
for (var i = 0; i < width; i += 1) {
for (var j = 0; j < height; j += 1) {
var pureIndex = j * width + i;
var index = pureIndex * channels;
// no. of pixels per window
var x1 = i - s2;
var x2 = i + s2;
var y1 = j - s2;
var y2 = j + s2;
if (x1 < 0)
x1 = 0;
if (x2 >= width)
x2 = width - 1;
if (y1 < 0)
y1 = 0;
if (y2 >= height)
y2 = height - 1;
var count = (x2 - x1) * (y2 - y1);
var sum = integralImage[y2 * width + x2] -
integralImage[y1 * width + x2] -
integralImage[y2 * width + x1] +
integralImage[y1 * width + x1];
var v = 255;
if (data[index] * count < sum * (1 - t)) {
v = 0;
}
data[index] = v;
data[index + 1] = v;
data[index + 2] = v;
}
}
return data;
}
function applySimpleThreshold(data, width, height) {
var channels = data.length / (width * height);
for (var i = 0; i < data.length; i += channels) {
var r = data[i];
var g = data[i + 1];
var b = data[i + 2];
var v = (r + g + b) / 3;
v = v >= 127 ? 255 : 0;
data[i] = v;
data[i + 1] = v;
data[i + 2] = v;
}
return data;
}
var isTestEnv = process && process.env.NODE_ENV === 'test';
const isTestEnv = process && process.env.NODE_ENV === 'test';
(function (BARCODE_DECODERS) {

@@ -1165,86 +1149,69 @@ BARCODE_DECODERS["code-128"] = "code-128";

}
function javascriptBarcodeReader(_a) {
var image = _a.image, barcode = _a.barcode, barcodeType = _a.barcodeType, options = _a.options;
return __awaiter(this, void 0, void 0, function () {
var decoder$7, useSinglePass, imageData, _b, width, height, data, channels, finalResult, sPoints, slineStep, rowsToScan, i, sPoint, start, end, dataSlice, lines, result;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
switch (barcode) {
case exports.BARCODE_DECODERS.codabar:
decoder$7 = decoder;
break;
case exports.BARCODE_DECODERS['code-128']:
decoder$7 = decoder$1;
break;
case exports.BARCODE_DECODERS['code-39']:
decoder$7 = decoder$2;
break;
case exports.BARCODE_DECODERS['code-93']:
decoder$7 = decoder$3;
break;
case exports.BARCODE_DECODERS['code-2of5']:
decoder$7 = decoder$4;
break;
case exports.BARCODE_DECODERS['ean-13']:
decoder$7 = decoder$5;
break;
case exports.BARCODE_DECODERS['ean-8']:
decoder$7 = decoder$6;
break;
default:
throw new Error("Invalid barcode specified. Available decoders: " + exports.BARCODE_DECODERS + ".");
}
useSinglePass = isTestEnv || (options && options.singlePass) || false;
if (!isImageLike(image)) return [3 /*break*/, 1];
_b = image;
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, getImageDataFromSource(image)];
case 2:
_b = _c.sent();
_c.label = 3;
case 3:
imageData = _b;
width = imageData.width;
height = imageData.height;
data = imageData.data;
channels = data.length / (width * height);
finalResult = '';
// apply adaptive threshold
if (options && options.useAdaptiveThreshold) {
data = applyAdaptiveThreshold(data, width, height);
}
sPoints = [5, 6, 4, 7, 3, 8, 2, 9, 1];
slineStep = Math.round(height / sPoints.length);
rowsToScan = Math.min(5, height);
for (i = 0; i < sPoints.length; i += 1) {
sPoint = sPoints[i];
start = channels * width * Math.floor(slineStep * sPoint);
end = start + rowsToScan * channels * width;
dataSlice = data.slice(start, end);
if (!options || !options.useAdaptiveThreshold) {
dataSlice = applySimpleThreshold(dataSlice, width, height);
}
lines = getLines(dataSlice, width, rowsToScan);
if (lines.length === 0) {
if (useSinglePass)
throw new Error('Failed to extract barcode!');
continue;
}
result = decoder$7(lines, barcodeType);
if (useSinglePass)
return [2 /*return*/, result];
if (!result)
continue;
if (!result.includes('?'))
return [2 /*return*/, result];
finalResult = combineAllPossible(finalResult, result);
if (!finalResult.includes('?'))
return [2 /*return*/, finalResult];
if (i === sPoints.length - 1)
return [2 /*return*/, finalResult];
}
function javascriptBarcodeReader({ image, barcode, barcodeType, options, }) {
return __awaiter(this, void 0, void 0, function* () {
let decoder$7;
switch (barcode) {
case exports.BARCODE_DECODERS.codabar:
decoder$7 = decoder;
break;
case exports.BARCODE_DECODERS['code-128']:
decoder$7 = decoder$1;
break;
case exports.BARCODE_DECODERS['code-39']:
decoder$7 = decoder$2;
break;
case exports.BARCODE_DECODERS['code-93']:
decoder$7 = decoder$3;
break;
case exports.BARCODE_DECODERS['code-2of5']:
decoder$7 = decoder$4;
break;
case exports.BARCODE_DECODERS['ean-13']:
decoder$7 = decoder$5;
break;
case exports.BARCODE_DECODERS['ean-8']:
decoder$7 = decoder$6;
break;
default:
throw new Error(`Invalid barcode specified. Available decoders: ${exports.BARCODE_DECODERS}.`);
}
const useSinglePass = isTestEnv || (options && options.singlePass) || false;
const imageData = isImageLike(image) ? image : yield getImageDataFromSource(image);
const width = imageData.width;
const height = imageData.height;
const channels = imageData.data.length / (width * height);
let finalResult = '';
// apply adaptive threshold
if (options && options.useAdaptiveThreshold) {
applyAdaptiveThreshold(imageData.data, width, height);
}
// check points for barcode location
const sPoints = [5, 6, 4, 7, 3, 8, 2, 9, 1];
const slineStep = Math.round(height / sPoints.length);
const rowsToScan = Math.min(3, height);
for (let i = 0; i < sPoints.length; i += 1) {
const sPoint = sPoints[i];
const start = channels * width * Math.floor(slineStep * sPoint);
const end = start + rowsToScan * channels * width;
const lines = getLines(imageData.data.slice(start, end), width, rowsToScan);
if (lines.length === 0) {
if (useSinglePass)
throw new Error('Failed to extract barcode!');
continue;
}
});
// Run the decoder
const result = decoder$7(lines, barcodeType);
if (useSinglePass)
return result;
if (!result)
continue;
if (!result.includes('?'))
return result;
finalResult = combineAllPossible(finalResult, result);
if (!finalResult.includes('?'))
return finalResult;
if (i === sPoints.length - 1)
return finalResult;
}
throw new Error('Failed to extract barcode!');
});

@@ -1251,0 +1218,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CHAR_SET = {
const CHAR_SET = {
nnnnnww: '0',

@@ -23,11 +23,11 @@ nnnnwwn: '1',

nwnwnnw: 'C',
nnnwwwn: 'D'
nnnwwwn: 'D',
};
function decoder(lines) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return (pre + item) / 2; }, 0));
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => (pre + item) / 2, 0));
// Read one encoded character at a time.
while (lines.length > 0) {
var seg = lines.splice(0, 8).splice(0, 7);
var a = seg.map(function (line) { return (line < barThreshold ? 'n' : 'w'); }).join('');
const seg = lines.splice(0, 8).splice(0, 7);
const a = seg.map(line => (line < barThreshold ? 'n' : 'w')).join('');
code.push(CHAR_SET[a]);

@@ -34,0 +34,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WIDTH_TBL = [
const WIDTH_TBL = [
'212222',

@@ -112,5 +112,5 @@ '222122',

'211133',
'2331112'
'2331112',
];
var TBL_A = [
const TBL_A = [
' ',

@@ -223,5 +223,5 @@ '!',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var TBL_B = [
const TBL_B = [
' ',

@@ -334,5 +334,5 @@ '!',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var TBL_C = [
const TBL_C = [
'00',

@@ -445,18 +445,24 @@ '01',

'Stop',
'Reverse Stop'
'Reverse Stop',
];
var computeGroup = function (lines) {
var factor = lines.reduce(function (pre, item) { return pre + item; }, 0) / (Math.ceil(lines.length / 6) * 11);
// factor = Math.round(factor * 10) / 10
return lines.map(function (item) { return Math.round(item / factor) || 1; });
const computeGroup = (lines) => {
const count = lines.length - 13;
const factor = lines.reduce((pre, item, i) => {
if (i >= count)
return pre;
return pre + item;
}, 0) /
(Math.ceil(count / 6) * 11);
console.log(factor);
return lines.map(item => Math.round(item / factor) || 1);
};
function decoder(lines) {
var lookupTBL = TBL_B;
const code = [];
let lookupTBL = TBL_B;
// let sumOP = 0
var letterKey;
var letterCode;
var letterCodePrev;
var keyIndex;
var code = [];
var computedLines = computeGroup(lines);
let letterKey;
let letterCode;
let letterCodePrev;
let keyIndex;
const computedLines = computeGroup(lines);
if (!computedLines)

@@ -466,8 +472,5 @@ return '';

computedLines.pop();
// skip check code and stop code using -12
for (var i = 0; i * 6 < computedLines.length - 12; i += 1) {
// skip check code and stop code using -13
for (let i = 0; i * 6 < computedLines.length - 13; i += 1) {
letterKey = computedLines.slice(i * 6, (i + 1) * 6).join('');
if (letterKey === '114141') {
letterKey = '113141';
}
keyIndex = WIDTH_TBL.indexOf(letterKey);

@@ -506,2 +509,3 @@ letterCode = lookupTBL[keyIndex];

// if (sumOP % 103 !== WIDTH_TBL.indexOf(letterKey)) return ''
console.log('CODE: ', code.join(''));
return code.join('');

@@ -508,0 +512,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CHAR_SET = {
const CHAR_SET = {
nnnwwnwnn: '0',

@@ -47,12 +47,12 @@ wnnwnnnnw: '1',

nnnwnwnwn: '%',
nwnnwnwnn: '*'
nwnnwnwnn: '*',
};
function decoder(lines) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return pre + item; }, 0) / lines.length);
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => pre + item, 0) / lines.length);
// Read one encoded character at a time.
while (lines.length > 0) {
var sequenceBar = lines
const sequenceBar = lines
.splice(0, 10)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map(line => (line > barThreshold ? 'w' : 'n'))
.slice(0, 9)

@@ -59,0 +59,0 @@ .join('');

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CHAR_SET = [
const CHAR_SET = [
{ '100010100': '0' },

@@ -51,11 +51,11 @@ { '101001000': '1' },

{ '100110010': '(+)' },
{ '101011110': '*' }
{ '101011110': '*' },
];
function decoder(lines) {
var code = [];
var binary = [];
const code = [];
const binary = [];
// remove termination bar
lines.pop();
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return pre + item; }, 0) / lines.length);
var minBarWidth = Math.ceil(lines.reduce(function (pre, item) {
const barThreshold = Math.ceil(lines.reduce((pre, item) => pre + item, 0) / lines.length);
const minBarWidth = Math.ceil(lines.reduce((pre, item) => {
if (item < barThreshold)

@@ -66,4 +66,4 @@ return (pre + item) / 2;

// leave the padded *
for (var i = 0; i < lines.length; i += 1) {
var segment = lines[i];
for (let i = 0; i < lines.length; i += 1) {
let segment = lines[i];
while (segment > 0) {

@@ -79,18 +79,15 @@ if (i % 2 === 0) {

}
var _loop_1 = function (i) {
var searcKey = binary.slice(i, i + 9).join('');
var char = CHAR_SET.filter(function (item) { return Object.keys(item)[0] === searcKey; });
for (let i = 0; i < binary.length; i += 9) {
const searcKey = binary.slice(i, i + 9).join('');
const char = CHAR_SET.filter(item => Object.keys(item)[0] === searcKey);
code.push(char[0][searcKey]);
};
for (var i = 0; i < binary.length; i += 9) {
_loop_1(i);
}
if (code.shift() !== '*' || code.pop() !== '*')
return '';
var K = code.pop();
var sum = 0;
var letter;
var Value;
var findValue = function (item) { return Object.values(item)[0] === letter; };
for (var i = code.length - 1; i >= 0; i -= 1) {
const K = code.pop();
let sum = 0;
let letter;
let Value;
const findValue = (item) => Object.values(item)[0] === letter;
for (let i = code.length - 1; i >= 0; i -= 1) {
letter = code[i];

@@ -102,5 +99,5 @@ Value = CHAR_SET.indexOf(CHAR_SET.filter(findValue)[0]);

return '';
var C = code.pop();
const C = code.pop();
sum = 0;
for (var i = code.length - 1; i >= 0; i -= 1) {
for (let i = code.length - 1; i >= 0; i -= 1) {
letter = code[i];

@@ -107,0 +104,0 @@ Value = CHAR_SET.indexOf(CHAR_SET.filter(findValue)[0]);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CHAR_SET = [
const CHAR_SET = [
'nnwwn',

@@ -13,16 +13,16 @@ 'wnnnw',

'wnnwn',
'nwnwn'
'nwnwn',
];
function decoder(lines, type) {
var code = [];
var barThreshold = Math.ceil(lines.reduce(function (pre, item) { return (pre + item) / 2; }, 0));
const code = [];
const barThreshold = Math.ceil(lines.reduce((pre, item) => (pre + item) / 2, 0));
if (type === 'interleaved') {
// extract start/ends pair
var startChar = lines
const startChar = lines
.splice(0, 4)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');
var endChar = lines
const endChar = lines
.splice(lines.length - 3, 3)
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -33,11 +33,11 @@ if (startChar !== 'nnnn' || endChar !== 'wnn')

while (lines.length > 0) {
var seg = lines.splice(0, 10);
var a = seg
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
const seg = lines.splice(0, 10);
const a = seg
.filter((item, index) => index % 2 === 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');
code.push(CHAR_SET.indexOf(a));
var b = seg
.filter(function (item, index) { return index % 2 !== 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
const b = seg
.filter((item, index) => index % 2 !== 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -49,11 +49,11 @@ code.push(CHAR_SET.indexOf(b));

// extract start/ends pair
var startChar = lines
const startChar = lines
.splice(0, 6)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');
var endChar = lines
const endChar = lines
.splice(lines.length - 5, 5)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map((line) => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -64,6 +64,6 @@ if (startChar !== 'wwn' || endChar !== 'wnw')

while (lines.length > 0) {
var a = lines
const a = lines
.splice(0, 10)
.filter(function (item, index) { return index % 2 === 0; })
.map(function (line) { return (line > barThreshold ? 'w' : 'n'); })
.filter((item, index) => index % 2 === 0)
.map(line => (line > barThreshold ? 'w' : 'n'))
.join('');

@@ -70,0 +70,0 @@ code.push(CHAR_SET.indexOf(a));

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var UPC_SET = {
const UPC_SET = {
'3211': '0',

@@ -13,8 +13,8 @@ '2221': '1',

'1213': '8',
'3112': '9'
'3112': '9',
};
function decoder(lines) {
var code = '';
let code = '';
// start indicator/reference lines
var bar = (lines[0] + lines[1] + lines[2]) / 3;
const bar = (lines[0] + lines[1] + lines[2]) / 3;
// remove start pattern

@@ -30,8 +30,6 @@ lines.shift();

lines.splice(24, 5);
for (var i = 0; i < lines.length; i += 4) {
var group = lines.slice(i, i + 4);
var digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(function (digit) {
return digit === 1.5 ? 1 : Math.round(digit);
});
var result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
for (let i = 0; i < lines.length; i += 4) {
const group = lines.slice(i, i + 4);
const digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(digit => digit === 1.5 ? 1 : Math.round(digit));
const result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
if (result) {

@@ -38,0 +36,0 @@ code += result;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var UPC_SET = {
const UPC_SET = {
'3211': '0',

@@ -13,8 +13,8 @@ '2221': '1',

'1213': '8',
'3112': '9'
'3112': '9',
};
function decoder(lines) {
var code = '';
let code = '';
// start indicator/reference lines
var bar = (lines[0] + lines[1] + lines[2]) / 3;
const bar = (lines[0] + lines[1] + lines[2]) / 3;
// remove start pattern

@@ -30,8 +30,6 @@ lines.shift();

lines.splice(16, 5);
for (var i = 0; i < lines.length; i += 4) {
var group = lines.slice(i, i + 4);
var digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(function (digit) {
return digit === 1.5 ? 1 : Math.round(digit);
});
var result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
for (let i = 0; i < lines.length; i += 4) {
const group = lines.slice(i, i + 4);
const digits = [group[0] / bar, group[1] / bar, group[2] / bar, group[3] / bar].map(digit => digit === 1.5 ? 1 : Math.round(digit));
const result = UPC_SET[digits.join('')] || UPC_SET[digits.reverse().join('')];
if (result) {

@@ -38,0 +36,0 @@ code += result;

@@ -11,45 +11,16 @@ "use strict";

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
// available decoders
var codabar = require("./codabar");
var code128 = require("./code-128");
var code39 = require("./code-39");
var code93 = require("./code-93");
var code2of5 = require("./code2of5");
var ean13 = require("./ean-13");
var ean8 = require("./ean-8");
// utilities
var combineAllPossible_1 = require("./utilities/combineAllPossible");
var getImageDataFromSource_1 = require("./utilities/getImageDataFromSource");
var getLines_1 = require("./utilities/getLines");
var adaptiveThreshold_1 = require("./utilities/threshold/adaptiveThreshold");
var applySimpleThreshold_1 = require("./utilities/threshold/applySimpleThreshold");
var isTestEnv = process && process.env.NODE_ENV === 'test';
const codabar = require("./codabar");
const code128 = require("./code-128");
const code39 = require("./code-39");
const code93 = require("./code-93");
const code2of5 = require("./code2of5");
const ean13 = require("./ean-13");
const ean8 = require("./ean-8");
const adaptiveThreshold_1 = require("./utilities/adaptiveThreshold");
const combineAllPossible_1 = require("./utilities/combineAllPossible");
const getImageDataFromSource_1 = require("./utilities/getImageDataFromSource");
const getLines_1 = require("./utilities/getLines");
const isTestEnv = process && process.env.NODE_ENV === 'test';
var BARCODE_DECODERS;

@@ -68,86 +39,69 @@ (function (BARCODE_DECODERS) {

}
function javascriptBarcodeReader(_a) {
var image = _a.image, barcode = _a.barcode, barcodeType = _a.barcodeType, options = _a.options;
return __awaiter(this, void 0, void 0, function () {
var decoder, useSinglePass, imageData, _b, width, height, data, channels, finalResult, sPoints, slineStep, rowsToScan, i, sPoint, start, end, dataSlice, lines, result;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
switch (barcode) {
case BARCODE_DECODERS.codabar:
decoder = codabar.decoder;
break;
case BARCODE_DECODERS['code-128']:
decoder = code128.decoder;
break;
case BARCODE_DECODERS['code-39']:
decoder = code39.decoder;
break;
case BARCODE_DECODERS['code-93']:
decoder = code93.decoder;
break;
case BARCODE_DECODERS['code-2of5']:
decoder = code2of5.decoder;
break;
case BARCODE_DECODERS['ean-13']:
decoder = ean13.decoder;
break;
case BARCODE_DECODERS['ean-8']:
decoder = ean8.decoder;
break;
default:
throw new Error("Invalid barcode specified. Available decoders: " + BARCODE_DECODERS + ".");
}
useSinglePass = isTestEnv || (options && options.singlePass) || false;
if (!isImageLike(image)) return [3 /*break*/, 1];
_b = image;
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource(image)];
case 2:
_b = _c.sent();
_c.label = 3;
case 3:
imageData = _b;
width = imageData.width;
height = imageData.height;
data = imageData.data;
channels = data.length / (width * height);
finalResult = '';
// apply adaptive threshold
if (options && options.useAdaptiveThreshold) {
data = adaptiveThreshold_1.applyAdaptiveThreshold(data, width, height);
}
sPoints = [5, 6, 4, 7, 3, 8, 2, 9, 1];
slineStep = Math.round(height / sPoints.length);
rowsToScan = Math.min(5, height);
for (i = 0; i < sPoints.length; i += 1) {
sPoint = sPoints[i];
start = channels * width * Math.floor(slineStep * sPoint);
end = start + rowsToScan * channels * width;
dataSlice = data.slice(start, end);
if (!options || !options.useAdaptiveThreshold) {
dataSlice = applySimpleThreshold_1.applySimpleThreshold(dataSlice, width, height);
}
lines = getLines_1.getLines(dataSlice, width, rowsToScan);
if (lines.length === 0) {
if (useSinglePass)
throw new Error('Failed to extract barcode!');
continue;
}
result = decoder(lines, barcodeType);
if (useSinglePass)
return [2 /*return*/, result];
if (!result)
continue;
if (!result.includes('?'))
return [2 /*return*/, result];
finalResult = combineAllPossible_1.combineAllPossible(finalResult, result);
if (!finalResult.includes('?'))
return [2 /*return*/, finalResult];
if (i === sPoints.length - 1)
return [2 /*return*/, finalResult];
}
function javascriptBarcodeReader({ image, barcode, barcodeType, options, }) {
return __awaiter(this, void 0, void 0, function* () {
let decoder;
switch (barcode) {
case BARCODE_DECODERS.codabar:
decoder = codabar.decoder;
break;
case BARCODE_DECODERS['code-128']:
decoder = code128.decoder;
break;
case BARCODE_DECODERS['code-39']:
decoder = code39.decoder;
break;
case BARCODE_DECODERS['code-93']:
decoder = code93.decoder;
break;
case BARCODE_DECODERS['code-2of5']:
decoder = code2of5.decoder;
break;
case BARCODE_DECODERS['ean-13']:
decoder = ean13.decoder;
break;
case BARCODE_DECODERS['ean-8']:
decoder = ean8.decoder;
break;
default:
throw new Error(`Invalid barcode specified. Available decoders: ${BARCODE_DECODERS}.`);
}
const useSinglePass = isTestEnv || (options && options.singlePass) || false;
const imageData = isImageLike(image) ? image : yield getImageDataFromSource_1.getImageDataFromSource(image);
const width = imageData.width;
const height = imageData.height;
const channels = imageData.data.length / (width * height);
let finalResult = '';
// apply adaptive threshold
if (options && options.useAdaptiveThreshold) {
adaptiveThreshold_1.applyAdaptiveThreshold(imageData.data, width, height);
}
// check points for barcode location
const sPoints = [5, 6, 4, 7, 3, 8, 2, 9, 1];
const slineStep = Math.round(height / sPoints.length);
const rowsToScan = Math.min(3, height);
for (let i = 0; i < sPoints.length; i += 1) {
const sPoint = sPoints[i];
const start = channels * width * Math.floor(slineStep * sPoint);
const end = start + rowsToScan * channels * width;
const lines = getLines_1.getLines(imageData.data.slice(start, end), width, rowsToScan);
if (lines.length === 0) {
if (useSinglePass)
throw new Error('Failed to extract barcode!');
continue;
}
});
// Run the decoder
const result = decoder(lines, barcodeType);
if (useSinglePass)
return result;
if (!result)
continue;
if (!result.includes('?'))
return result;
finalResult = combineAllPossible_1.combineAllPossible(finalResult, result);
if (!finalResult.includes('?'))
return finalResult;
if (i === sPoints.length - 1)
return finalResult;
}
throw new Error('Failed to extract barcode!');
});

@@ -154,0 +108,0 @@ }

@@ -7,5 +7,5 @@ "use strict";

}
var finalResultArr = finalResult.split('');
var resultArr = result.split('');
resultArr.forEach(function (char, index) {
const finalResultArr = finalResult.split('');
const resultArr = result.split('');
resultArr.forEach((char, index) => {
if (!finalResultArr[index] || finalResultArr[index] === '?') {

@@ -12,0 +12,0 @@ if (char && char !== '?') {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function createImageData(image) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx)
throw new Error('canvas not available');
var width = image.naturalWidth;
var height = image.naturalHeight;
const width = image.naturalWidth;
const height = image.naturalHeight;
canvas.width = width;

@@ -11,0 +11,0 @@ canvas.height = height;

@@ -11,84 +11,55 @@ "use strict";

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Jimp = require("jimp");
var createImageData_1 = require("./createImageData");
var isUrl_1 = require("./isUrl");
var isNode = typeof process === 'object' && process.release && process.release.name === 'node';
const Jimp = require("jimp");
const createImageData_1 = require("./createImageData");
const isUrl_1 = require("./isUrl");
const isNode = typeof process === 'object' && process.release && process.release.name === 'node';
function getImageDataFromSource(source) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
if (typeof source === 'string') {
if (source.startsWith('#')) {
var imageElement = document.getElementById(source.substr(1));
if (imageElement instanceof HTMLImageElement) {
resolve(createImageData_1.createImageData(imageElement));
}
if (imageElement instanceof HTMLCanvasElement) {
var ctx = imageElement.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, imageElement.width, imageElement.height));
}
reject(new Error('Invalid image source specified!'));
}
else if (isUrl_1.isUrl(source)) {
var img_1 = new Image();
img_1.onerror = reject;
img_1.onload = function () { return resolve(createImageData_1.createImageData(img_1)); };
img_1.src = source;
}
else if (isNode) {
Jimp.read(source, function (err, image) {
if (err) {
reject(err);
}
else {
var _a = image.bitmap, data = _a.data, width = _a.width, height = _a.height;
resolve({
data: Uint8ClampedArray.from(data),
width: width,
height: height
});
}
});
}
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (typeof source === 'string') {
if (source.startsWith('#')) {
const imageElement = document.getElementById(source.substr(1));
if (imageElement instanceof HTMLImageElement) {
resolve(createImageData_1.createImageData(imageElement));
}
else if (source instanceof HTMLImageElement) {
resolve(createImageData_1.createImageData(source));
}
else if (source instanceof HTMLCanvasElement) {
var ctx = source.getContext('2d');
if (imageElement instanceof HTMLCanvasElement) {
const ctx = imageElement.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, source.width, source.height));
resolve(ctx.getImageData(0, 0, imageElement.width, imageElement.height));
}
})];
reject(new Error('Invalid image source specified!'));
}
else if (isUrl_1.isUrl(source)) {
const img = new Image();
img.onerror = reject;
img.onload = () => resolve(createImageData_1.createImageData(img));
img.src = source;
}
else if (isNode) {
Jimp.read(source, (err, image) => {
if (err) {
reject(err);
}
else {
const { data, width, height } = image.bitmap;
resolve({
data: Uint8ClampedArray.from(data),
width,
height,
});
}
});
}
}
else if (source instanceof HTMLImageElement) {
resolve(createImageData_1.createImageData(source));
}
else if (source instanceof HTMLCanvasElement) {
const ctx = source.getContext('2d');
if (!ctx)
throw new Error('Cannot create canvas 2d context');
resolve(ctx.getImageData(0, 0, source.width, source.height));
}
});

@@ -95,0 +66,0 @@ });

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const medianFilter_1 = require("./medianFilter");
function getLines(data, width, height) {
var channels = data.length / (width * height);
var lines = [];
var count = 0;
var colSum = 0;
var colAvg = 0;
var colAvgLast = 0;
for (var col = 0; col < width; col += 1) {
colSum = 0;
for (var row = 0; row < height; row += 1) {
colSum += data[(row * width + col) * channels];
const dataSlice = medianFilter_1.applyMedianFilter(data, width, height);
const channels = dataSlice.length / (width * height);
const lines = [];
let count = 0;
let columnAverageLast = 0;
for (let column = 0; column < width; column += 1) {
let columnSum = 0;
let columnAverage = 0;
for (let row = 0; row < height; row += 1) {
const index = (row * width + column) * channels;
columnSum += Math.sqrt((Math.pow(data[index], 2) + Math.pow(data[index + 1], 2) + Math.pow(data[index + 2], 2)) / 3);
}
// atleast 75% of the pixels are same in column
colAvg = colSum / height >= 127 ? 255 : 0;
// skip white padding in the start
if (count === 0 && colAvg === 255)
// pixels are same in column
columnAverage = columnSum / height >= 127 ? 255 : 0;
// skip white padding in the start & end
if (columnAverage === 255 && count === 0)
continue;
// count line width
if (colAvg === colAvgLast) {
if (columnAverage === columnAverageLast) {
count += 1;

@@ -26,7 +28,7 @@ }

lines.push(count);
columnAverageLast = columnAverage;
count = 1;
colAvgLast = colAvg;
}
// skip padding in the last
if (col === width - 1 && colAvg === 0) {
if (column === width - 1 && columnAverage === 0) {
lines.push(count);

@@ -33,0 +35,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
if (s.startsWith('#'))

@@ -6,0 +6,0 @@ return false;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function applyMedianFilter(data, width, height) {
var channels = data.length / (width * height);
var window = [
[-1, -1],
[-1, 0],
[-1, 1],
[0, -1],
[0, 0],
[0, 1],
[1, -1],
[1, 0],
[1, 1]
];
for (var col = 1; col < width - 1; col += 1) {
for (var row = 1; row < height - 1; row += 1) {
var i = (row * width + col) * channels;
var arr = [];
for (var z = 0; z < window.length; z += 1) {
var i_1 = ((row + window[z][0]) * width + (col + window[z][1])) * channels;
var v_1 = (data[i_1] + data[i_1 + 1] + data[i_1 + 2]) / 3;
arr.push(v_1);
function applyMedianFilter(data, width, height, windowSize = 3) {
const channels = data.length / (width * height);
const filterWindow = [];
const limit = (windowSize - 1) / 2;
for (let i = limit * -1; i < limit + 1; i += 1) {
for (let j = limit * -1; j < limit + 1; j += 1) {
filterWindow.push([i, j]);
}
}
for (let col = limit; col < width - limit; col += 1) {
for (let row = limit; row < height - limit; row += 1) {
const index = (row * width + col) * channels;
const arr = [];
for (let z = 0; z < filterWindow.length; z += 1) {
const i = ((row + filterWindow[z][0]) * width + (col + filterWindow[z][1])) * channels;
const average = Math.sqrt((Math.pow(data[i], 2) + Math.pow(data[i + 1], 2) + Math.pow(data[i + 2], 2)) / 3);
arr.push(average);
}
var v = arr.sort(function (a, b) { return a - b; })[4] >= 127 ? 255 : 0;
data[i] = v;
data[i + 1] = v;
data[i + 2] = v;
const sorted = arr.sort((a, b) => a - b);
const medianValue = sorted[Math.floor(sorted.length / 2)];
// const thresholdValue = medianValue >= 180 ? 255 : 0
data[index + 0] = medianValue;
data[index + 1] = medianValue;
data[index + 2] = medianValue;
if (channels === 4)
data[index + 3] = 255;
}

@@ -30,0 +30,0 @@ }

@@ -11,47 +11,18 @@ "use strict";

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Jimp = require("jimp");
var path = require("path");
var index_1 = require("../src/index");
var combineAllPossible_1 = require("../src/utilities/combineAllPossible");
var getImageDataFromSource_1 = require("../src/utilities/getImageDataFromSource");
var isUrl_1 = require("../src/utilities/isUrl");
var median_1 = require("../src/utilities/median");
var medianFilter_1 = require("../src/utilities/medianFilter");
const Jimp = require("jimp");
const path = require("path");
const index_1 = require("../src/index");
const combineAllPossible_1 = require("../src/utilities/combineAllPossible");
const getImageDataFromSource_1 = require("../src/utilities/getImageDataFromSource");
const getLines_1 = require("../src/utilities/getLines");
const isUrl_1 = require("../src/utilities/isUrl");
const medianFilter_1 = require("../src/utilities/medianFilter");
function loadImage(src) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
var img = new Image();
img.onerror = reject;
img.onload = function () { return resolve(img); };
img.src = src;
})];
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const img = new Image();
img.onerror = reject;
img.onload = () => resolve(img);
img.src = src;
});

@@ -61,126 +32,97 @@ });

function loadCanvas(img) {
var canvas = document.createElement('canvas');
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext('2d');
const ctx = canvas.getContext('2d');
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0);
return canvas;
}
beforeAll(function () { return __awaiter(void 0, void 0, void 0, function () {
var imageUrl, img, canvas;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
imageUrl = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png';
return [4 /*yield*/, loadImage(imageUrl)];
case 1:
img = _a.sent();
img.id = 'Code_93_wikipedia_image';
canvas = loadCanvas(img);
canvas.id = 'Code_93_wikipedia_canvas';
document.body.appendChild(img);
document.body.appendChild(canvas);
return [2 /*return*/];
}
});
}); });
describe('get imageData from source', function () {
test('should get imageData from url', function () { return __awaiter(void 0, void 0, void 0, function () {
var url, dataSource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png';
return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource(url)];
case 1:
dataSource = _a.sent();
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
return [2 /*return*/];
}
});
}); });
test('should get imageData from file path', function () { return __awaiter(void 0, void 0, void 0, function () {
var url, dataSource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = path.resolve('./test/sample-images/codabar.jpg');
return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource(url)];
case 1:
dataSource = _a.sent();
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
return [2 /*return*/];
}
});
}); });
test('should get imageData from HTMLImageElement id', function () { return __awaiter(void 0, void 0, void 0, function () {
var dataSource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource('#Code_93_wikipedia_image')];
case 1:
dataSource = _a.sent();
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
return [2 /*return*/];
}
});
}); });
test('should get imageData from HTMLCanvasElement id', function () { return __awaiter(void 0, void 0, void 0, function () {
var dataSource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource('#Code_93_wikipedia_canvas')];
case 1:
dataSource = _a.sent();
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
return [2 /*return*/];
}
});
}); });
test('should get imageData from HTMLImageElement', function () { return __awaiter(void 0, void 0, void 0, function () {
var imageElement, dataSource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
imageElement = document.getElementById('Code_93_wikipedia_image');
if (!imageElement || !(imageElement instanceof HTMLImageElement))
return [2 /*return*/];
return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource(imageElement)];
case 1:
dataSource = _a.sent();
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
return [2 /*return*/];
}
});
}); });
test('should get imageData from HTMLCanvasElement', function () { return __awaiter(void 0, void 0, void 0, function () {
var imageElement, dataSource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
imageElement = document.getElementById('Code_93_wikipedia_canvas');
if (!imageElement || !(imageElement instanceof HTMLCanvasElement))
return [2 /*return*/];
return [4 /*yield*/, getImageDataFromSource_1.getImageDataFromSource(imageElement)];
case 1:
dataSource = _a.sent();
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
return [2 /*return*/];
}
});
}); });
test('should throw with invalid source', function () {
getImageDataFromSource_1.getImageDataFromSource('Olalalala').catch(function (err) {
beforeAll(() => __awaiter(void 0, void 0, void 0, function* () {
const imageUrl = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png';
const img = yield loadImage(imageUrl);
img.id = 'Code_93_wikipedia_image';
const canvas = loadCanvas(img);
canvas.id = 'Code_93_wikipedia_canvas';
document.body.appendChild(img);
document.body.appendChild(canvas);
}));
describe('Count lines in an image', () => {
test('should detect lines in barcode image', () => __awaiter(void 0, void 0, void 0, function* () {
const rowsToScan = 3;
const image = yield Jimp.read('./test/sample-images/small-padding.png');
const { data, width, height } = image.bitmap;
const channels = data.length / (width * height);
const startIndex = channels * width * Math.floor(height / 2);
const endIndex = startIndex + rowsToScan * channels * width;
const lines = getLines_1.getLines(Uint8ClampedArray.from(data.slice(startIndex, endIndex)), width, rowsToScan);
expect(lines.length).toBe(27);
}));
test('should detect lines in barcode image without padding', () => __awaiter(void 0, void 0, void 0, function* () {
const rowsToScan = 3;
const image = yield Jimp.read('./test/sample-images/small.png');
const { data, width, height } = image.bitmap;
const channels = data.length / (width * height);
const startIndex = channels * width * Math.floor(height / 2);
const endIndex = startIndex + rowsToScan * channels * width;
const lines = getLines_1.getLines(Uint8ClampedArray.from(data.slice(startIndex, endIndex)), width, rowsToScan);
expect(lines.length).toBe(27);
}));
test('should return zero lines with empty image', () => __awaiter(void 0, void 0, void 0, function* () {
const rowsToScan = 3;
const image = yield Jimp.read('./test/sample-images/empty.jpg');
const { data, width, height } = image.bitmap;
const channels = data.length / (width * height);
const startIndex = channels * width * Math.floor(height / 2);
const endIndex = startIndex + rowsToScan * channels * width;
const lines = getLines_1.getLines(Uint8ClampedArray.from(data.slice(startIndex, endIndex)), width, rowsToScan);
expect(lines.length).toBe(0);
}));
});
describe('get imageData from source', () => {
test('should get imageData from url', () => __awaiter(void 0, void 0, void 0, function* () {
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png';
const dataSource = yield getImageDataFromSource_1.getImageDataFromSource(url);
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
}));
test('should get imageData from file path', () => __awaiter(void 0, void 0, void 0, function* () {
const url = path.resolve('./test/sample-images/codabar.jpg');
const dataSource = yield getImageDataFromSource_1.getImageDataFromSource(url);
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
}));
test('should get imageData from HTMLImageElement id', () => __awaiter(void 0, void 0, void 0, function* () {
const dataSource = yield getImageDataFromSource_1.getImageDataFromSource('#Code_93_wikipedia_image');
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
}));
test('should get imageData from HTMLCanvasElement id', () => __awaiter(void 0, void 0, void 0, function* () {
const dataSource = yield getImageDataFromSource_1.getImageDataFromSource('#Code_93_wikipedia_canvas');
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
}));
test('should get imageData from HTMLImageElement', () => __awaiter(void 0, void 0, void 0, function* () {
const imageElement = document.getElementById('Code_93_wikipedia_image');
if (!imageElement || !(imageElement instanceof HTMLImageElement))
return;
const dataSource = yield getImageDataFromSource_1.getImageDataFromSource(imageElement);
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
}));
test('should get imageData from HTMLCanvasElement', () => __awaiter(void 0, void 0, void 0, function* () {
const imageElement = document.getElementById('Code_93_wikipedia_canvas');
if (!imageElement || !(imageElement instanceof HTMLCanvasElement))
return;
const dataSource = yield getImageDataFromSource_1.getImageDataFromSource(imageElement);
expect(typeof dataSource.data).toBe('object');
expect(typeof dataSource.width).toBe('number');
expect(typeof dataSource.height).toBe('number');
}));
test('should throw with invalid source', () => {
getImageDataFromSource_1.getImageDataFromSource('Olalalala').catch(err => {
expect(err).toBeDefined();

@@ -190,14 +132,14 @@ });

});
describe('Median Filter', function () {
test('Apply median filter to imageData', function () {
var width = 9;
var height = 9;
var data = new Array(width * height).fill(undefined).map(function () { return Math.random() * 255; });
var dataMedian = medianFilter_1.applyMedianFilter(Uint8ClampedArray.from(data), width, height);
describe('Median Filter', () => {
test('Apply median filter to imageData', () => {
const width = 9;
const height = 9;
const data = new Array(width * height).fill(undefined).map(() => Math.random() * 255);
const dataMedian = medianFilter_1.applyMedianFilter(Uint8ClampedArray.from(data), width, height);
expect(dataMedian.length).toBe(width * height);
});
});
describe('isUrl', function () {
test('check if string is URL', function () {
var url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png';
describe('isUrl', () => {
test('check if string is URL', () => {
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png';
expect(isUrl_1.isUrl(url)).toBeTruthy();

@@ -207,11 +149,5 @@ expect(isUrl_1.isUrl('#someString')).toBeFalsy();

});
describe('median', function () {
test('get median of array', function () {
expect(median_1.median([6, 3, 9])).toBe(6);
expect(median_1.median([9, 3, 6])).toBe(6);
});
});
describe('combineAllPossible', function () {
test('should be able to combine multiple results into one complete', function () {
var result = combineAllPossible_1.combineAllPossible('?123456', '012345?');
describe('combineAllPossible', () => {
test('should be able to combine multiple results into one complete', () => {
const result = combineAllPossible_1.combineAllPossible('?123456', '012345?');
expect(result).toBe('0123456');

@@ -221,395 +157,213 @@ expect(combineAllPossible_1.combineAllPossible('', '')).toBe('');

});
describe('extract barcode from local files', function () {
test('should detect barcode codabar', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/codabar.jpg'),
barcode: index_1.BARCODE_DECODERS.codabar
})];
case 1:
result = _a.sent();
expect(result).toBe('A40156C');
return [2 /*return*/];
}
describe('extract barcode from local files', () => {
test('should detect barcode codabar', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/codabar.jpg'),
barcode: index_1.BARCODE_DECODERS.codabar,
});
}); });
test('should detect barcode codabar', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/codabar.jpg'),
barcode: index_1.BARCODE_DECODERS.codabar,
options: {
singlePass: true
}
})];
case 1:
result = _a.sent();
expect(result).toBe('A40156C');
return [2 /*return*/];
}
expect(result).toBe('A40156C');
}));
test('should detect barcode codabar', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/codabar.jpg'),
barcode: index_1.BARCODE_DECODERS.codabar,
options: {
singlePass: true,
},
});
}); });
test('should detect barcode 2 of 5 standard', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5.jpg'),
barcode: 'code-2of5'
})];
case 1:
result = _a.sent();
expect(result).toBe('12345670');
return [2 /*return*/];
}
expect(result).toBe('A40156C');
}));
test('should detect barcode 2 of 5 standard', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5.jpg'),
barcode: 'code-2of5',
});
}); });
test('should detect barcode 2 of 5 interleaved', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5-interleaved.jpg'),
barcode: 'code-2of5',
barcodeType: 'interleaved'
})];
case 1:
result = _a.sent();
expect(result).toBe('12345670');
return [2 /*return*/];
}
expect(result).toBe('12345670');
}));
test('should detect barcode 2 of 5 interleaved', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5-interleaved.jpg'),
barcode: 'code-2of5',
barcodeType: 'interleaved',
});
}); });
test('should detect barcode 39', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-39.jpg'),
barcode: 'code-39'
})];
case 1:
result = _a.sent();
expect(result).toBe('10023');
return [2 /*return*/];
}
expect(result).toBe('12345670');
}));
test('should detect barcode 39', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-39.jpg'),
barcode: 'code-39',
});
}); });
test('should detect barcode 93', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-93.jpg'),
barcode: 'code-93'
})];
case 1:
result = _a.sent();
expect(result).toBe('123ABC');
return [2 /*return*/];
}
expect(result).toBe('10023');
}));
test('should detect barcode 93', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-93.jpg'),
barcode: 'code-93',
});
}); });
test('should detect barcode 128: ABC-abc-1234', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128.jpg'),
barcode: 'code-128'
})];
case 1:
result = _a.sent();
expect(result).toBe('ABC-abc-1234');
return [2 /*return*/];
}
expect(result).toBe('123ABC');
}));
test('should detect barcode 128: ABC-abc-1234', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128.jpg'),
barcode: 'code-128',
});
}); });
test('should detect barcode 128: eeb00f0c-0c7e-a937-1794-25685779ba0c', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-eeb00f0c-0c7e-a937-1794-25685779ba0c.png'),
barcode: 'code-128'
})];
case 1:
result = _a.sent();
expect(result).toBe('eeb00f0c-0c7e-a937-1794-25685779ba0c');
return [2 /*return*/];
}
expect(result).toBe('ABC-abc-1234');
}));
test('should detect barcode 128: eeb00f0c-0c7e-a937-1794-25685779ba0c', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-eeb00f0c-0c7e-a937-1794-25685779ba0c.png'),
barcode: 'code-128',
});
}); });
test('should detect barcode EAN-8', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/ean-8.jpg'),
barcode: 'ean-8'
})];
case 1:
result = _a.sent();
expect(result).toBe('73127727');
return [2 /*return*/];
}
expect(result).toBe('eeb00f0c-0c7e-a937-1794-25685779ba0c');
}));
test('should detect barcode 128: 3107cde3-d1ff-0f93-a215-4109753c0c9e', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-3107cde3-d1ff-0f93-a215-4109753c0c9e.png'),
barcode: 'code-128',
});
}); });
test('should detect barcode EAN-13 small', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/ean-13-5901234123457.png'),
barcode: 'ean-13'
})];
case 1:
result = _a.sent();
expect(result).toBe('901234123457');
return [2 /*return*/];
}
expect(result).toBe('3107cde3-d1ff-0f93-a215-4109753c0c9e');
}));
test('should detect barcode EAN-8', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/ean-8.jpg'),
barcode: 'ean-8',
options: {
useAdaptiveThreshold: true,
},
});
}); });
test('should detect barcode EAN-13 large', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/ean-13.jpg'),
barcode: 'ean-13'
})];
case 1:
result = _a.sent();
expect(result).toBe('901234123457');
return [2 /*return*/];
}
expect(result).toBe('73127727');
}));
test('should detect barcode EAN-13 small', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/ean-13-5901234123457.png'),
barcode: 'ean-13',
});
}); });
test('should detect barcode 128 without padding white bars', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-no-padding.jpg'),
barcode: 'code-128'
})];
case 1:
result = _a.sent();
expect(result).toBe('12ab#!');
return [2 /*return*/];
}
expect(result).toBe('901234123457');
}));
test('should detect barcode EAN-13 large', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/ean-13.jpg'),
barcode: 'ean-13',
});
}); });
test('should detect barcode 128 with multiple zeros', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-000.jpg'),
barcode: 'code-128'
})];
case 1:
result = _a.sent();
expect(result).toBe('79619647103200000134407005');
return [2 /*return*/];
}
expect(result).toBe('901234123457');
}));
test('should detect barcode 128 without padding white bars', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-no-padding.jpg'),
barcode: 'code-128',
});
}); });
test('should detect barcode 128 with default start Code B', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/L89HE1806005080432.gif'),
barcode: 'code-128'
})];
case 1:
result = _a.sent();
expect(result).toBe('L89HE1806005080432');
return [2 /*return*/];
}
expect(result).toBe('12ab#!');
}));
test('should detect barcode 128 with multiple zeros', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-128-000.jpg'),
barcode: 'code-128',
});
}); });
test('should detect barcode 93 without padding white bars', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-93-no-padding.jpg'),
barcode: 'code-93'
})];
case 1:
result = _a.sent();
expect(result).toBe('WIKIPEDIA');
return [2 /*return*/];
}
expect(result).toBe('79619647103200000134407005');
}));
test('should detect barcode 128 with default start Code B', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/L89HE1806005080432.gif'),
barcode: 'code-128',
});
}); });
test('should detect barcode 93 with bitmap data', function () { return __awaiter(void 0, void 0, void 0, function () {
var image, _a, data, width, height, result;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, Jimp.read('./test/sample-images/code-93-no-padding.jpg')];
case 1:
image = _b.sent();
_a = image.bitmap, data = _a.data, width = _a.width, height = _a.height;
return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: {
data: Uint8ClampedArray.from(data),
width: width,
height: height
},
barcode: 'code-93'
})];
case 2:
result = _b.sent();
expect(result).toBe('WIKIPEDIA');
return [2 /*return*/];
}
expect(result).toBe('L89HE1806005080432');
}));
test('should detect barcode 93 without padding white bars', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-93-no-padding.jpg'),
barcode: 'code-93',
});
}); });
expect(result).toBe('WIKIPEDIA');
}));
test('should detect barcode 93 with bitmap data', () => __awaiter(void 0, void 0, void 0, function* () {
const image = yield Jimp.read('./test/sample-images/code-93-no-padding.jpg');
const { data, width, height } = image.bitmap;
const result = yield index_1.javascriptBarcodeReader({
image: {
data: Uint8ClampedArray.from(data),
width,
height,
},
barcode: 'code-93',
});
expect(result).toBe('WIKIPEDIA');
}));
});
describe('extract barcode after applying adaptive threhsold', function () {
test('should detect barcode codabar', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/codabar.jpg'),
barcode: 'codabar',
options: {
useAdaptiveThreshold: true
}
})];
case 1:
result = _a.sent();
expect(result).toBe('A40156C');
return [2 /*return*/];
}
describe('extract barcode after applying adaptive threhsold', () => {
test('should detect barcode codabar', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/codabar.jpg'),
barcode: 'codabar',
options: {
useAdaptiveThreshold: true,
},
});
}); });
test('should detect barcode 2 of 5', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5.jpg'),
barcode: 'code-2of5',
options: {
useAdaptiveThreshold: true
}
})];
case 1:
result = _a.sent();
expect(result).toBe('12345670');
return [2 /*return*/];
}
expect(result).toBe('A40156C');
}));
test('should detect barcode 2 of 5', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5.jpg'),
barcode: 'code-2of5',
options: {
useAdaptiveThreshold: true,
},
});
}); });
test('should detect barcode 2 of 5 interleaved', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5-interleaved.jpg'),
barcode: 'code-2of5',
barcodeType: 'interleaved',
options: {
useAdaptiveThreshold: true
}
})];
case 1:
result = _a.sent();
expect(result).toBe('12345670');
return [2 /*return*/];
}
expect(result).toBe('12345670');
}));
test('should detect barcode 2 of 5 interleaved', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: path.resolve('./test/sample-images/code-2of5-interleaved.jpg'),
barcode: 'code-2of5',
barcodeType: 'interleaved',
options: {
useAdaptiveThreshold: true,
},
});
}); });
expect(result).toBe('12345670');
}));
});
describe('extract barcode from remote URL', function () {
test('should detect barcode 93 from remote url', function () { return __awaiter(void 0, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png',
barcode: 'code-93'
})];
case 1:
result = _a.sent();
expect(result).toBe('WIKIPEDIA');
return [2 /*return*/];
}
describe('extract barcode from remote URL', () => {
test('should detect barcode 93 from remote url', () => __awaiter(void 0, void 0, void 0, function* () {
const result = yield index_1.javascriptBarcodeReader({
image: 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png',
barcode: 'code-93',
});
}); });
expect(result).toBe('WIKIPEDIA');
}));
});
describe('Fails', function () {
test('throws when no barcode specified', function () { return __awaiter(void 0, void 0, void 0, function () {
var err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png',
barcode: 'oallal'
})];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
expect(err_1).toBeDefined();
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
test('throws when invalid barcode specified', function () { return __awaiter(void 0, void 0, void 0, function () {
var err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: './test/sample-images/empty.jpg',
barcode: 'none'
})];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_2 = _a.sent();
expect(err_2).toBeDefined();
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
test('throws when no barcode found', function () { return __awaiter(void 0, void 0, void 0, function () {
var err_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, index_1.javascriptBarcodeReader({
image: './test/sample-images/empty.jpg',
barcode: 'code-93'
})];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_3 = _a.sent();
expect(err_3).toBeDefined();
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
describe('Fails', () => {
test('throws when no barcode specified', () => __awaiter(void 0, void 0, void 0, function* () {
try {
yield index_1.javascriptBarcodeReader({
image: 'https://upload.wikimedia.org/wikipedia/en/a/a9/Code_93_wikipedia.png',
barcode: 'oallal',
});
}
catch (err) {
expect(err).toBeDefined();
}
}));
test('throws when invalid barcode specified', () => __awaiter(void 0, void 0, void 0, function* () {
try {
yield index_1.javascriptBarcodeReader({
image: './test/sample-images/empty.jpg',
barcode: 'none',
});
}
catch (err) {
expect(err).toBeDefined();
}
}));
test('throws when no barcode found', () => __awaiter(void 0, void 0, void 0, function* () {
try {
yield index_1.javascriptBarcodeReader({
image: './test/sample-images/empty.jpg',
barcode: 'code-93',
});
}
catch (err) {
expect(err).toBeDefined();
}
}));
});
//# sourceMappingURL=index.test.js.map

@@ -24,3 +24,3 @@ export declare enum BARCODE_DECODERS {

};
export declare function javascriptBarcodeReader({ image, barcode, barcodeType, options }: JavascriptBarcodeReader): Promise<string>;
export declare function javascriptBarcodeReader({ image, barcode, barcodeType, options, }: JavascriptBarcodeReader): Promise<string>;
export {};

@@ -1,1 +0,1 @@

export declare function applyMedianFilter(data: Uint8ClampedArray, width: number, height: number): Uint8ClampedArray;
export declare function applyMedianFilter(data: Uint8ClampedArray, width: number, height: number, windowSize?: number): Uint8ClampedArray;

@@ -18,6 +18,6 @@ {

"devDependencies": {
"@babel/core": "^7.8.4",
"@babel/core": "^7.8.6",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/plugin-proposal-object-rest-spread": "^7.8.3",
"@babel/preset-env": "^7.8.4",
"@babel/preset-env": "^7.8.6",
"@commitlint/cli": "^8.3.5",

@@ -30,13 +30,10 @@ "@commitlint/config-conventional": "^8.3.4",

"@types/jest": "^25.1.3",
"@types/lodash.camelcase": "^4.3.6",
"@types/node": "^13.7.6",
"@types/node": "^13.7.7",
"@types/nodemon": "^1.19.0",
"@types/prettier": "^1.19.0",
"@types/rimraf": "^2.0.3",
"@types/rollup-plugin-json": "^3.0.2",
"@types/semantic-release": "^15.13.1",
"@types/shelljs": "^0.8.6",
"@typescript-eslint/eslint-plugin": "^2.21.0",
"@typescript-eslint/parser": "^2.21.0",
"canvas": "^2.6.1",
"colors": "^1.4.0",
"commitizen": "^4.0.3",

@@ -55,8 +52,5 @@ "coveralls": "^3.0.9",

"lint-staged": "^10.0.8",
"lodash.camelcase": "^4.3.0",
"nodemon": "^2.0.2",
"prettier": "^1.19.1",
"prompt": "^1.0.0",
"replace-in-file": "^5.0.2",
"rimraf": "^3.0.2",
"rollup": "^1.31.1",
"rollup": "^1.32.0",
"rollup-plugin-json": "^4.0.0",

@@ -67,7 +61,6 @@ "rollup-plugin-node-resolve": "^5.2.0",

"semantic-release": "^17.0.4",
"shelljs": "^0.8.3",
"ts-jest": "^25.2.1",
"ts-node": "^8.6.2",
"typedoc": "^0.16.10",
"typescript": "^3.8.2"
"typedoc": "^0.16.11",
"typescript": "^3.8.3"
},

@@ -78,45 +71,6 @@ "engines": {

"files": [
"src",
"dist"
],
"homepage": "https://github.com/mubaidr/Javascript-Barcode-Reader#readme",
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,ts}"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"/test/",
"/dist/",
"/docs/",
"/tools/"
],
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 100,
"lines": 90,
"statements": 90
}
},
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testEnvironment": "jsdom",
"testEnvironmentOptions": {
"resources": "usable"
},
"testPathIgnorePatterns": [
"/node_modules/",
"/src/",
"/dist/",
"/docs/",
"/tools/"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"transform": {
".(ts|tsx)": "ts-jest"
}
},
"keywords": [

@@ -139,6 +93,2 @@ "barcode",

"name": "javascript-barcode-reader",
"prettier": {
"semi": false,
"singleQuote": true
},
"repository": {

@@ -152,3 +102,3 @@ "type": "git",

"deploy-docs": "ts-node tools/gh-pages-publish",
"lint": "eslint --ext .js,.ts {src,test}/* --fix && prettier --write \"{test,src}/**/*.{js,ts}\"",
"lint": "eslint --ext .js,.ts {src,test}/* --fix && prettier --write \"{test,src,tools}/**/*.{js,ts}\"",
"prebuild": "rimraf dist",

@@ -165,3 +115,3 @@ "precommit": "lint-staged",

"typings": "dist/types/javascript-barcode-reader.d.ts",
"version": "0.6.2"
"version": "0.6.3"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc