Reinstar
Reinstar

Reputation: 146

Create qrCode with output base64 from javascript

I want to create qr-code with output base64 string from javascript.

I found http://davidshimjs.github.io/qrcodejs/ for generate qr-code. That I want is get base64 string from this awesome tools.

Upvotes: 5

Views: 37475

Answers (4)

Lalo19
Lalo19

Reputation: 137

Install the library qrcode https://www.npmjs.com/package/qrcode

Instalation command: npm i qrcode

Then use the next code:

    const QRCode = require('qrcode');

    let QRbase64 = await new Promise((resolve, reject) => {
        QRCode.toDataURL('I love tacos!!', function (err, code) {
            if (err) {
                reject(reject);
                return;
            }
            resolve(code);
        });
    });
    
    console.log(QRbase64);

Upvotes: 4

Balaji
Balaji

Reputation: 10877

just use below given any one of the qr js library to get base64

1.qrcodejs

2.easyqrcodejs

var qrcodjs = new QRCode("qrcode", {
    text: orderData.reference,
    width: 128,
    height: 128,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.H
});

base64

qrcode._oDrawing._elCanvas.toDataURL("image/png")

Upvotes: 2

you can get the Base64 directly from the generated variable, i.e.:

/*generate QRCode*/
var qrcodjs = new QRCode("qrcode", {
    text: orderData.reference,
    width: 128,
    height: 128,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.H
});

/*get base64*/
var imgBase64Data = qrcodjs._el.childNodes[4].currentSrc;

This will work unfortunately only on google chrome or Firefox... for IE or Safari you will have to use:

                var imgBase64 = qrcodjs._oDrawing._elImage.currentSrc;
                if (typeof imgBase64 === "undefined")
                    imgBase64 = qrcodjs._oDrawing._elImage.href;
                if (typeof imgBase64 === "undefined")
                    imgBase64 = qrcodjs._oDrawing._elImage.src;

Upvotes: 2

oshliaer
oshliaer

Reputation: 4969

May be you can get this code d-project.googlecode.com

And replace last strings

from

    var img = '';
    img += '<img';
    img += '\u0020src="';
    img += 'data:image/gif;base64,';
    img += base64;
    img += '"';
    img += '\u0020width="';
    img += width;
    img += '"';
    img += '\u0020height="';
    img += height;
    img += '"';
    if (alt) {
        img += '\u0020alt="';
        img += alt;
        img += '"';
    }
    img += '/>';

to

    var img = 'data:image/gif;base64,' + base64;

Getting a base64

    var qr = qrcode(4, 'M');
    qr.addData('This is base64 string');
    qr.make();
    concole.log(qr.createImgTag());

Upvotes: 1

Related Questions