Move parsing and generation of QR codes to lib folder.

Also rewrote QR code parsing to be more readable and actually error out properly.
This commit is contained in:
j433866 2019-03-07 13:21:26 +00:00
parent 8148c1a8a8
commit 21a8d03201
3 changed files with 96 additions and 80 deletions

View file

@ -7,8 +7,7 @@
import Operation from "../Operation";
import OperationError from "../errors/OperationError";
import Magic from "../lib/Magic";
import jsqr from "jsqr";
import jimp from "jimp";
import { parseQrCode } from "../lib/QRCode";
/**
* Parse QR Code operation
@ -42,64 +41,13 @@ class ParseQRCode extends Operation {
* @returns {string}
*/
async run(input, args) {
const type = Magic.magicFileType(input);
const [normalise] = args;
const type = Magic.magicFileType(input);
// Make sure that the input is an image
if (type && type.mime.indexOf("image") === 0) {
let image = input;
if (normalise) {
// Process the image to be easier to read by jsqr
// Disables the alpha channel
// Sets the image default background to white
// Normalises the image colours
// Makes the image greyscale
// Converts image to a JPEG
image = await new Promise((resolve, reject) => {
jimp.read(Buffer.from(input))
.then(image => {
image
.rgba(false)
.background(0xFFFFFFFF)
.normalize()
.greyscale()
.getBuffer(jimp.MIME_JPEG, (error, result) => {
resolve(result);
});
})
.catch(err => {
reject(new OperationError("Error reading the image file."));
});
});
}
if (image instanceof OperationError) {
throw image;
}
return new Promise((resolve, reject) => {
jimp.read(Buffer.from(image))
.then(image => {
if (image.bitmap != null) {
const qrData = jsqr(image.bitmap.data, image.getWidth(), image.getHeight());
if (qrData != null) {
resolve(qrData.data);
} else {
reject(new OperationError("Couldn't read a QR code from the image."));
}
} else {
reject(new OperationError("Error reading the image file."));
}
})
.catch(err => {
reject(new OperationError("Error reading the image file."));
});
});
} else {
if (!type || type.mime.indexOf("image") !== 0) {
throw new OperationError("Invalid file type.");
}
return await parseQrCode(input, normalise);
}
}