我正在努力从node.js中上传的图像中读取多个条形码。为此,我正在使用javascript-barcode-reader,它需要 ImageData 作为输入。要获取图像的 ImageData ,我必须使用node-canvas(,因为我必须在Nodejs中完成所有操作,而不是在前端中完成)。
波纹管代码的执行没有任何警告/错误。目前,我仅使用单个条形码图像,但是我将code
设为空。
这里出了什么问题,为什么我得到 null 值。
const Canvas = require('canvas');
const javascriptBarcodeReader = require('javascript-barcode-reader');
var filepath = './images/Code-2of5.jpg';
var buf = fs.readFileSync(filepath);
var canvas = new Canvas(640, 480);
var Image = Canvas.Image;
var ctx = canvas.getContext('2d');
fs.readFileSync(filepath, function (err, squid) {
if (err) throw err;
let img = new Image;
img.src = squid;
img.onload = function () {
ctx.drawImage(img, 0, 0, 640, 480);
}
});
let imgData = ctx.getImageData(0, 0, 640, 480);
const code = javascriptBarcodeReader(imgData /* ImageData */ , {
barcode: 'code-2of5', // 'code-128'
type: 'interleaved', //standard/interleaved optional type
});
console.log(code); // output as null
最初,我仅尝试获取单个条形码图像。
答案 0 :(得分:1)
这里有2个陷阱:
img.src
处理程序之前分配img.onload
。同时检查此工作示例的同步版本和承诺版本
const fs = require('fs');
const Canvas = require('canvas');
const javascriptBarcodeReader = require('javascript-barcode-reader');
function readBarCodeSync(imagePath) {
const canvas = new Canvas(640, 480);
const Image = Canvas.Image;
const ctx = canvas.getContext('2d');
const img = new Image;
img.onload = function () {
ctx.drawImage(img, 0, 0, 640, 480);
}
img.src = fs.readFileSync(imagePath);
const imgData = ctx.getImageData(0, 0, 640, 480);
const code = javascriptBarcodeReader(imgData /* ImageData */ , {
barcode: 'code-2of5', // 'code-128'
type: 'interleaved', //standard/interleaved optional type
});
return code;
}
function readBarCode (imagePath) {
const canvas = new Canvas(640, 480);
const Image = Canvas.Image;
const ctx = canvas.getContext('2d');
const img = new Image;
img.onload = function () {
ctx.drawImage(img, 0, 0, 640, 480);
}
return new Promise((resolve,reject)=>{
fs.readFile(imagePath,(err,buf)=>{
if(err) return reject(err);
img.src = buf;
const imgData = ctx.getImageData(0, 0, 640, 480);
const code = javascriptBarcodeReader(imgData /* ImageData */ , {
barcode: 'code-2of5', // 'code-128'
type: 'interleaved', //standard/interleaved optional type
});
resolve(code);
});
});
}
var imagePath = './images/Code-2of5.jpg';
console.log('sync version', readBarCodeSync(imagePath))
readBarCode(imagePath)
.then(barCode=>{
console.log('async version', barCode);
})
.catch(err=>{
console.error(err);
})