CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-zxing--library

TypeScript port of ZXing multi-format 1D/2D barcode image processing library

Overview
Eval results
Files

index.mddocs/

@zxing/library

TypeScript port of the ZXing multi-format 1D/2D barcode image processing library. Provides comprehensive barcode decoding (reading) and encoding (writing) capabilities for 17 different barcode formats with support for both browser and Node.js environments.

Package Information

  • Package: @zxing/library
  • Type: npm
  • Language: TypeScript
  • Installation: npm install @zxing/library
  • Formats: ESM, CommonJS, UMD
  • Node.js: >= 10.4.0

Quick Start

Decode Barcode from Image

import {
  MultiFormatReader,
  BinaryBitmap,
  HybridBinarizer,
  RGBLuminanceSource
} from '@zxing/library';

const luminanceSource = new RGBLuminanceSource(imagePixels, width, height);
const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
const reader = new MultiFormatReader();

try {
  const result = reader.decode(binaryBitmap);
  console.log('Decoded:', result.getText());
  console.log('Format:', result.getBarcodeFormat());
} catch (error) {
  console.error('No barcode found:', error);
}

Encode QR Code

import {
  QRCodeWriter,
  BarcodeFormat,
  EncodeHintType,
  QRCodeDecoderErrorCorrectionLevel
} from '@zxing/library';

const writer = new QRCodeWriter();
const hints = new Map();
hints.set(EncodeHintType.ERROR_CORRECTION, QRCodeDecoderErrorCorrectionLevel.H);

const bitMatrix = writer.encode(
  'https://example.com',
  BarcodeFormat.QR_CODE,
  300,
  300,
  hints
);

// Render: matrix.get(x, y) returns true for black pixels

Browser Camera Scanning

import { BrowserMultiFormatReader } from '@zxing/library';

const codeReader = new BrowserMultiFormatReader();
const videoElement = document.getElementById('video') as HTMLVideoElement;

const result = await codeReader.decodeOnceFromVideoDevice(undefined, videoElement);
console.log('Scanned:', result.getText());
codeReader.reset(); // Release camera

Full Quick Start Guide

Supported Formats

2D Barcodes (Matrix)

FormatReadWriteDescription
QR CodeSquare matrix, 21×21 to 177×177 modules, 4 error correction levels
Data MatrixSquare/rectangular, ECC200, 10×10 to 144×144 modules
AztecBulls-eye center, compact (1-4 layers) or full (1-32 layers)
PDF417Stacked linear, 3-90 rows, 9 error correction levels
MaxiCodeFixed size, circular finder (not implemented)

1D Barcodes (Linear)

FormatReadWriteDescription
EAN-1313 digits, retail products worldwide
EAN-88 digits, small packages
UPC-A12 digits, North American retail
UPC-E8 digits, zero-suppressed UPC-A
Code 128High-density alphanumeric, shipping/logistics
Code 39Alphanumeric + symbols, automotive/military
Code 93Compact alphanumeric, logistics
ITFNumeric only, interleaved pairs, warehousing
CodabarNumeric + symbols, libraries/blood banks
RSS-1414-digit GTIN, compact for small items
RSS ExpandedVariable length with AIs (⚠️ experimental)

Core APIs

Readers

class MultiFormatReader implements Reader {
  decode(image: BinaryBitmap, hints?: Map<DecodeHintType, any>): Result;
  decodeWithState(image: BinaryBitmap): Result;
  setHints(hints: Map<DecodeHintType, any> | null): void;
  reset(): void;
}

class QRCodeReader implements Reader {
  decode(image: BinaryBitmap, hints?: Map<DecodeHintType, any>): Result;
  reset(): void;
}

class DataMatrixReader implements Reader {
  decode(image: BinaryBitmap, hints?: Map<DecodeHintType, any>): Result;
  reset(): void;
}

class AztecCodeReader implements Reader {
  decode(image: BinaryBitmap, hints?: Map<DecodeHintType, any>): Result;
  reset(): void;
}

class PDF417Reader implements Reader, MultipleBarcodeReader {
  decode(image: BinaryBitmap, hints?: Map<DecodeHintType, any>): Result;
  decodeMultiple(image: BinaryBitmap, hints?: Map<DecodeHintType, any>): Result[];
  reset(): void;
}

Writers

class MultiFormatWriter implements Writer {
  encode(
    contents: string,
    format: BarcodeFormat,
    width: number,
    height: number,
    hints: Map<EncodeHintType, any>
  ): BitMatrix;
}

class QRCodeWriter implements Writer {
  encode(
    contents: string,
    format: BarcodeFormat,
    width: number,
    height: number,
    hints?: Map<EncodeHintType, any>
  ): BitMatrix;
}

class DataMatrixWriter implements Writer {
  encode(
    contents: string,
    format: BarcodeFormat,
    width: number,
    height: number,
    hints?: Map<EncodeHintType, any>
  ): BitMatrix;
}

class AztecCodeWriter implements Writer {
  encode(
    contents: string,
    format: BarcodeFormat,
    width: number,
    height: number,
    hints?: Map<EncodeHintType, any>
  ): BitMatrix;
}

Image Processing

class BinaryBitmap {
  constructor(binarizer: Binarizer);
  getWidth(): number;
  getHeight(): number;
  getBlackRow(y: number, row: BitArray | null): BitArray;
  getBlackMatrix(): BitMatrix;
  isCropSupported(): boolean;
  crop(left: number, top: number, width: number, height: number): BinaryBitmap;
}

abstract class LuminanceSource {
  abstract getRow(y: number, row?: Uint8ClampedArray): Uint8ClampedArray;
  abstract getMatrix(): Uint8ClampedArray;
  abstract invert(): LuminanceSource;
  getWidth(): number;
  getHeight(): number;
}

class RGBLuminanceSource extends LuminanceSource {
  constructor(
    luminances: Uint8ClampedArray | Int32Array,
    width: number,
    height: number,
    dataWidth?: number,
    dataHeight?: number,
    left?: number,
    top?: number
  );
}

class HybridBinarizer extends Binarizer {
  constructor(source: LuminanceSource);
}

Result Types

class Result {
  constructor(
    text: string,
    rawBytes: Uint8Array | null,
    numBits: number,
    resultPoints: ResultPoint[],
    format: BarcodeFormat,
    timestamp: number
  );
  getText(): string;
  getRawBytes(): Uint8Array | null;
  getBarcodeFormat(): BarcodeFormat;
  getResultMetadata(): Map<ResultMetadataType, Object>;
  getResultPoints(): ResultPoint[];
}

Configuration

Decode Hints

HintTypePurpose
POSSIBLE_FORMATSBarcodeFormat[]Limit to specific formats (improves performance)
TRY_HARDERbooleanMore thorough scanning (slower, more accurate)
PURE_BARCODEbooleanImage contains only barcode (faster)
CHARACTER_SETstringCharacter encoding (e.g., "UTF-8")

Encode Hints

HintTypePurpose
ERROR_CORRECTIONvariesQR: L/M/Q/H, Aztec: 0-100%, PDF417: 0-8
CHARACTER_SETstringCharacter encoding
MARGINnumberQuiet zone size in pixels
QR_VERSIONnumberQR Code version 1-40
AZTEC_LAYERSnumber-4 to -1 (compact), 0 (auto), 1-32 (full)
DATA_MATRIX_SHAPESymbolShapeHintFORCE_SQUARE or FORCE_RECTANGLE

Common Patterns

See Real-World Scenarios and Edge Cases for complete examples of:

  • Multi-strategy decoding with fallbacks
  • Batch processing with reader reuse
  • Continuous camera scanning
  • Error recovery patterns
  • Performance optimization

Error Handling

ExceptionCauseAction
NotFoundExceptionNo barcode foundCheck image quality, try TRY_HARDER
ChecksumExceptionToo many errorsRetry with better image
FormatExceptionInvalid structureCheck barcode not obscured
WriterExceptionEncoding failedCheck data size/format
try {
  const result = reader.decode(bitmap);
} catch (error) {
  if (error instanceof NotFoundException) {
    // No barcode found
  } else if (error instanceof ChecksumException) {
    // Barcode damaged
  }
}

Architecture

  1. Core Layer: MultiFormatReader, MultiFormatWriter - auto-detect formats
  2. Format Layer: Format-specific readers/writers (QR, Data Matrix, Aztec, PDF417, 1D formats)
  3. Image Processing: LuminanceSourceBinarizerBinaryBitmap
  4. Detection: Pattern detection, perspective transformation, grid sampling
  5. Error Correction: Reed-Solomon for 2D barcodes
  6. Browser: Camera access (deprecated, moving to @zxing/browser)

Documentation

Guides

Examples

API Reference

Core APIs:

Format-Specific:

Utilities:

Format Selection Guide

When to Use Each Format

QR Code: General purpose, mobile apps, marketing, maximum compatibility

  • Capacity: Up to 2,953 bytes
  • Error correction: 4 levels (L ~7%, M ~15%, Q ~25%, H ~30%)
  • Best for: URLs, contact info, WiFi credentials, app deep links

Data Matrix: Manufacturing, healthcare, electronics, small items

  • Capacity: Up to 2,335 alphanumeric characters
  • Error correction: ECC200 automatic
  • Best for: Component marking, PCB tracking, pharmaceutical labeling

Aztec: Transport tickets, ID documents, high data density

  • Capacity: Up to 3,832 numeric digits
  • Error correction: Configurable 23-90%
  • Best for: Boarding passes, event tickets, government IDs

PDF417: Driver licenses, shipping labels, inventory (decode only)

  • Capacity: Up to 1,850 text characters
  • Error correction: 9 levels (0-8)
  • Best for: ID cards, transport documents, bulk data

1D Barcodes: Retail products, inventory, legacy systems

  • EAN-13/UPC-A: Retail products
  • Code 128: Shipping, packaging, general purpose
  • Code 39: Industrial applications
  • ITF: Distribution, warehousing

Common Decode Hints

const hints = new Map();

// Limit to specific formats (improves performance)
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
  BarcodeFormat.QR_CODE,
  BarcodeFormat.EAN_13
]);

// Enable accuracy mode
  hints.set(DecodeHintType.TRY_HARDER, true);
  
// Specify character encoding
hints.set(DecodeHintType.CHARACTER_SET, 'UTF-8');

// Pure barcode image (no detection needed, faster)
hints.set(DecodeHintType.PURE_BARCODE, true);

Common Encode Hints

const hints = new Map();

// QR Code: Set error correction level
hints.set(EncodeHintType.ERROR_CORRECTION, 'H'); // L, M, Q, or H

// Set character encoding
hints.set(EncodeHintType.CHARACTER_SET, 'UTF-8');

// Set margin/quiet zone
hints.set(EncodeHintType.MARGIN, 4); // In modules

// QR Code: Force specific version
hints.set(EncodeHintType.QR_VERSION, 10); // 1-40

// Aztec: Set layer count
hints.set(EncodeHintType.AZTEC_LAYERS, 0); // 0=auto, negative=compact, positive=full

// Data Matrix: Force square shape
hints.set(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE);

Binarization Strategy

Choose between two binarizers:

HybridBinarizer (recommended default):

  • Local block-based thresholding
  • Handles shadows and gradients
  • Best for: 2D barcodes, challenging lighting, general purpose

GlobalHistogramBinarizer:

  • Single global threshold
  • Faster but less accurate
  • Best for: Uniform lighting, 1D barcodes, low-end devices
// Recommended (more accurate)
const binarizer = new HybridBinarizer(luminanceSource);

// Faster alternative
const binarizer = new GlobalHistogramBinarizer(luminanceSource);

Exception Handling

import {
  NotFoundException,
  FormatException,
  ChecksumException,
  WriterException
} from '@zxing/library';

try {
  const result = reader.decode(bitmap);
  // Success
  } catch (error) {
  if (error instanceof NotFoundException) {
    // No barcode found - check image quality
  } else if (error instanceof ChecksumException) {
    // Barcode damaged - retry with TRY_HARDER
  } else if (error instanceof FormatException) {
    // Invalid barcode structure
  } else if (error instanceof WriterException) {
    // Encoding failed - check data size/format compatibility
  }
}

Browser Notes

Deprecation: Browser-specific classes are moving to @zxing/browser package:

  • BrowserMultiFormatReader → Use from @zxing/browser
  • BrowserQRCodeReader → Use from @zxing/browser
  • Other Browser* classes → Use from @zxing/browser

Camera Requirements:

  • HTTPS required (except localhost)
  • Handle permission errors gracefully
  • Always call reset() to release camera

Performance Tips

  1. Reuse reader instances - avoid creating new readers for each decode
  2. Set hints once - use setHints() + decodeWithState() for batch processing
  3. Limit formats - use POSSIBLE_FORMATS hint when format is known
  4. Choose binarizer - GlobalHistogramBinarizer faster, HybridBinarizer more accurate
  5. Crop images - crop to barcode region before decoding when possible

Capacity Reference

FormatNumericAlphanumericBinary
QR Code (v40, L)7,0894,2962,953 bytes
Data Matrix (144×144)3,1162,3351,555 bytes
Aztec (32 layers, 33% ECC)~3,800~3,000~1,500 bytes
PDF417 (max)2,7101,8501,108 bytes

Further Reading

Install with Tessl CLI

npx tessl i tessl/npm-zxing--library

docs

index.md

tile.json