This repository was archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscanner.js
More file actions
96 lines (89 loc) · 2.72 KB
/
Copy pathscanner.js
File metadata and controls
96 lines (89 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const QrCode = require('qrcode-reader');
const Jimp = require("jimp");
const jsqr = require("jsqr");
const request = require('request').defaults({ encoding: null }); //null encoding outputs a buffer
//configure QR
let qr = new QrCode();
qr.callback = function(error, result) {
if(error) {
console.error(error)
return;
}
console.log(result)
}
/**
* Downloads an image async and returns a buffer
* @param {string} url the URL to the image to download
* @return resolves the downloaded buffer
*/
async function downloadBuffer(url){
return new Promise(function(resolve,reject){
request.get(url, function (err, res, buffer) {
resolve(buffer);
});
});
}
/**
* Attempts to read an image at a URL as a QR code. Uses both qrcode-reader and jsqr
* @param {string} url url to the image
* @return resolves undefined if image could not be read as a QR code. Resolves with the contents if the
* image is a scannable QR code.
*/
async function scanURL(url){
return new Promise(async function(resolve,reject){
//download image
let buffer = await downloadBuffer(url);
//read it with Jimp
Jimp.read(buffer,async function(err,img){
if (err){
//silent catch errors
//console.error(err);
}
else{
//try the tests
let test1 = await JSQRScan(img.bitmap.data,img.bitmap.width,img.bitmap.height);
if (test1){
resolve(test1);
}
else{
resolve(QRCodeReaderScan(img.bitmap));
}
}
});
});
}
exports.scanURL = scanURL;
/**
* Attempts to read a QR code using qrcode-reader
* @param {Jimp.image} bitmap
* @return resolves with the value if it could be read, undefined if it could not
*/
async function QRCodeReaderScan(bitmap){
return new Promise(function(resolve,reject){
let qr = new QrCode();
qr.callback = function(err,value){
if (err){
//unable to scan the image as a QR code, so safe
resolve(undefined);
}
else{
resolve(value);
}
}
qr.decode(bitmap);
});
}
/**
* Attempts to read a QR code using jsQR
* @param {Uint8ClampedArray} uint8array image data
* @param {number} width the width in pixels of the image
* @param {number} height the height in pixels of the image
* @returns the data if there is any, or undefined
*/
function JSQRScan(uint8array,width,height){
let code = jsqr(uint8array,width,height,{inversionAttempts:"attemptBoth"});
if (code){
return code.data;
}
return undefined;
}