Decoding/Encoding QR Code With Pure JavaScript

Category: Javascript | May 30, 2019
Author: nuintun
Views Total: 210
Official Page: Go to website
Last Update: May 30, 2019
License: MIT

Preview:

Decoding/Encoding QR Code With Pure JavaScript

Description:

QR code encoder and decoder tools which helps you quickly generate QR codes from given contents and decode QR codes from images.

How to use it:

Install the package.

# Yarn
$ yarn add @nuintun/qrcode

# NPM
$ npm install @nuintun/qrcode --save

Import modules as per your needs.

// encoder
import { Encoder, QRByte, QRKanji, ErrorCorrectionLevel } from '@nuintun/qrcode';

// decoder
import { Decoder } from '@nuintun/qrcode';

Encoder

Generate a QR code from the content you provide.

const qrcode = new Encoder();

qrcode.write('你好世界\n');
qrcode.write(new QRByte('hello world\n'));
qrcode.write(new QRKanji('こんにちは世界'));

qrcode.make();

console.log(qrcode.toDataURL());

Customize the encoder with the following methods.

// set version
qrcode.setVersion(number);

// set the error correction level
// L, M, Q, H
setErrorCorrectionLevel(level);

// set qrcode encoding hint
setEncodingHint(hint);

More possible API methods for the encoder.

// get modules
qrcode.getModules();

// qet module count.
qrcode.getModuleCount();

// get version
qrcode.getVersion();

// get error correction level
qrcode.ggetErrorCorrectionLevel();

// get qrcode encoding hint
qrcode.getEncodingHint();

// add qrcode data
qrcode.write(QRByte | QRKanji | QRNumeric | QRAlphanumeric);

// get byte with row and col
qrcode.isDark(row: number, col: number);

// generate
qrcode.make();

// output base64 image
qrcode.toDataURL(moduleSize: number, margin: number)

Decoder:

Decode the QR code data from an image you provide.

const qrcode = new Decoder();

qrcode
  .scan('qrcode.jpg')
  .then(result => {
    console.log(result.data);
  })
  .catch(error => {
    console.error(result.data);
  });

Possible API methods.

const qrcode = new Decoder();

// set options
qrcode.setOptions({ 
  inversionAttempts: 'dontInvert' | 'onlyInvert' | 'attemptBoth' | 'invertFirst' 
});

// scan an image
qrcode.scan(src, promise);

// decode a qrcode from image data
decode(data: Uint8ClampedArray, width: number, height: number);

You Might Be Interested In:


Leave a Reply