3
votes

I have a backend Node.js endpoint that is supposed to accept images in base64 containing QR code and return a 16-digit alphanumeric string. (I'm using qrcode-reader package)

However, I'm encountering an error which says I need to pass an image buffer with width and height. I'm not sure how I can get the width and height from a base64 image-string, since many of the image packages on npm work with the files in .png or .jpg format.

Any suggestions on how I can obtain the width and height of an image in base64?

function readQR(){
    return function(req, res){
        // Load base64 image 
        var base64Image = req.body.image;
        var decodedImg = decodeBase64Image(base64Image);
        var imageBuffer = decodedImg.data;
        qr.callback = function(err, result){
            if(err) console.log(err);
            // Regex check whether it is 16 letter alphanumeric
            if(/^(\w{16,16})$/.test(result)) res.json(result);
            else res.json({
                error: 'Invalid dmac address'
            })
        }
        qr.decode(imageBuffer);
    }
}
1

1 Answers

2
votes

Seems like the simplest way to do this is to convert the base64 back to file and read the buffer. Managed to successfully read the qr code using the code below.

function readQR(){
    return function(req, res, next){

        var base64Image = req.body.image;   // Load base64 image 
        var decodedImg = decodeBase64Image(base64Image);
        var imageBuffer = new Buffer(decodedImg.data, 'base64');

        fs.writeFileSync(path.join(__dirname, '../', '/temp/image.jpg'), imageBuffer, {encoding: 'base64'}, function(err){
            if(err) console.log(err);
        });
        var buffer = fs.readFileSync(path.join(__dirname, '../', '/temp/image.jpg'));

        Jimp.read(buffer, function(error, image){
            if(error) console.log(error);
            qr.callback = function(err, value){
                if(err) console.log(err);
                console.log(value);
                if(/^(\w{16,16})$/.test(value.result)) res.json({dmac: value.result});
                else res.json({
                    error: 'Invalid dmac address'
                })
            };
            qr.decode(image.bitmap);
        })
    }
}