### Run Local Documentation Server
Source: https://github.com/zxing-js/library/blob/master/CONTRIBUTING.md
Use this command to serve the project's documentation locally. Ensure http-server is installed globally.
```bash
http-server ./docs -a localhost -p 4040 -o
```
--------------------------------
### Continuous QR Code Scanning with BrowserQRCodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Starts continuous QR code scanning from a video device. Handles decoding results and errors, including NotFoundException, ChecksumException, and FormatException. Ensure to call stopContinuousDecode() and reset() when finished.
```javascript
import { BrowserQRCodeReader, NotFoundException, ChecksumException, FormatException } from '@zxing/library';
const codeReader = new BrowserQRCodeReader();
// Start continuous scanning from camera
codeReader.decodeFromVideoDevice(null, 'video', (result, err) => {
if (result) {
console.log('Found QR code:', result.getText());
// Process the decoded result
}
if (err) {
if (err instanceof NotFoundException) {
// No barcode found in current frame - this is normal during scanning
console.log('Scanning...');
} else if (err instanceof ChecksumException) {
console.log('Barcode found but checksum invalid');
} else if (err instanceof FormatException) {
console.log('Barcode found but format invalid');
} else {
console.error('Unexpected error:', err);
}
}
});
// Stop continuous scanning when done
document.getElementById('stopButton').addEventListener('click', () => {
codeReader.stopContinuousDecode();
codeReader.reset();
});
```
--------------------------------
### Scan Aztec Code from Video Camera with ZXing TypeScript
Source: https://github.com/zxing-js/library/blob/master/docs/examples/aztec-camera/index.html
Use this code to initialize the Aztec code reader, list available video input devices, and start continuous decoding from the selected camera. It handles device selection and displays the decoded text or any errors encountered.
```typescript
window.addEventListener('load', function () {
let selectedDeviceId;
const codeReader = new ZXing.BrowserAztecCodeReader();
console.log('ZXing code reader initialized')
codeReader.getVideoInputDevices()
.then((videoInputDevices) => {
const sourceSelect = document.getElementById('sourceSelect')
selectedDeviceId = videoInputDevices[0].deviceId
if (videoInputDevices.length >= 1) {
videoInputDevices.forEach((element) => {
const sourceOption = document.createElement('option')
sourceOption.text = element.label
sourceOption.value = element.deviceId
sourceSelect.appendChild(sourceOption)
})
sourceSelect.onchange = () => {
selectedDeviceId = sourceSelect.value;
};
const sourceSelectPanel = document.getElementById('sourceSelectPanel')
sourceSelectPanel.style.display = 'block'
}
document.getElementById('startButton').addEventListener('click', () => {
codeReader.decodeFromInputVideoDevice(selectedDeviceId, 'video').then((result) => {
console.log(result)
document.getElementById('result').textContent = result.text
}).catch((err) => {
console.error(err)
document.getElementById('result').textContent = err
})
console.log(`Started continous decode from camera with id ${selectedDeviceId}`)
})
document.getElementById('resetButton').addEventListener('click', () => {
codeReader.reset()
document.getElementById('result').textContent = '';
console.log('Reset.')
})
})
.catch((err) => {
console.error(err)
})
});
```
--------------------------------
### List Video Input Devices with BrowserQRCodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Initializes the QR code reader and lists available video input devices. Use this to identify cameras before decoding.
```javascript
import { BrowserQRCodeReader } from '@zxing/library';
// Initialize the QR code reader
const codeReader = new BrowserQRCodeReader();
// List available video input devices
const videoInputDevices = await codeReader.listVideoInputDevices();
console.log('Available cameras:', videoInputDevices);
// Output: [{ deviceId: "abc123", label: "Front Camera" }, { deviceId: "def456", label: "Back Camera" }]
// Decode once from a specific camera
const selectedDeviceId = videoInputDevices[0].deviceId;
try {
const result = await codeReader.decodeOnceFromVideoDevice(selectedDeviceId, 'video-element-id');
console.log('Decoded text:', result.getText());
console.log('Barcode format:', result.getBarcodeFormat());
console.log('Result points:', result.getResultPoints());
} catch (err) {
console.error('Decoding failed:', err);
}
// Stop scanning and release camera
codeReader.reset();
```
--------------------------------
### Manage Camera Devices
Source: https://context7.com/zxing-js/library/llms.txt
List available video input devices and initiate scanning using specific device IDs or custom media constraints.
```javascript
import { BrowserMultiFormatReader } from '@zxing/library';
const codeReader = new BrowserMultiFormatReader();
// List all video input devices
const devices = await codeReader.listVideoInputDevices();
devices.forEach(device => {
console.log('Device ID:', device.deviceId);
console.log('Label:', device.label);
console.log('Group ID:', device.groupId);
console.log('---');
});
// Find a specific device by ID
const backCamera = await codeReader.findDeviceById('specific-device-id');
// Use environment-facing camera (default when deviceId is null)
await codeReader.decodeFromVideoDevice(null, 'video', callback);
// This will use facingMode: 'environment' automatically
// Use a specific camera
await codeReader.decodeFromVideoDevice(devices[1].deviceId, 'video', callback);
// Use custom media constraints
const constraints = {
video: {
facingMode: 'environment',
width: { ideal: 1280 },
height: { ideal: 720 }
}
};
await codeReader.decodeFromConstraints(constraints, 'video', (result, err) => {
if (result) console.log(result.getText());
});
```
--------------------------------
### Initialize and Control QR Code Video Decoding
Source: https://github.com/zxing-js/library/blob/master/docs/examples/qr-video/index.html
Uses BrowserQRCodeReader to decode a video source upon button click and provides a reset mechanism to clear the reader state.
```javascript
window.addEventListener('load', function () { const codeReader = new ZXing.BrowserQRCodeReader() console.log('ZXing code reader initialized') const resultContainer = document.getElementById('result') document.getElementById('startButton').addEventListener('click', async () => { const video = document.getElementById('video') video.setAttribute('src', '../../resources/qrcode-video.mp4') try { const result = await codeReader.decodeFromVideo(video) console.log(result) resultContainer.textContent = result.text } catch (err) { console.error(err) resultContainer.textContent = err } }) document.getElementById('resetButton').addEventListener('click', () => { codeReader.reset() resultContainer.textContent = '' console.log('Reset.') }) })
```
--------------------------------
### Initialize and Write QR Code to SVG
Source: https://github.com/zxing-js/library/blob/master/docs/examples/qr-svg-writer/index.html
Uses BrowserQRCodeSvgWriter to render input text as an SVG element and provides functionality to save the result as an SVG file.
```javascript
window.addEventListener('load', () => { const codeWriter = new ZXing.BrowserQRCodeSvgWriter() console.log('ZXing code writer initialized') let svgElement; document.getElementById('writeButton').addEventListener('click', () => { const input = document.getElementById('textInput').value svgElement = codeWriter.writeToDom('#result', input, 300, 300) document.getElementById('saveButton').removeAttribute('disabled') }) document.getElementById('saveButton').addEventListener('click', () => { const svgData = (new XMLSerializer()).serializeToString(document.getElementById('result')) const blob = new Blob([svgData]) saveAs(blob, 'zxing-qrcode-example.svg') }) })
```
--------------------------------
### Initialize ZXing BrowserBarcodeReader and Decode from Image
Source: https://github.com/zxing-js/library/blob/master/docs/examples/barcode-image/index.html
This code initializes the ZXing BrowserBarcodeReader and sets up event listeners to decode barcodes from images when a button is clicked. It handles both successful decoding and errors, displaying the result or error message.
```typescript
window.addEventListener('load', () => {
const codeReader = new ZXing.BrowserBarcodeReader();
console.log('ZXing code reader initialized');
const decodeFun = (e) => {
const parent = e.target.parentNode.parentNode;
const img = parent.getElementsByClassName('img')[0].cloneNode(true);
const resultEl = parent.getElementsByClassName('result')[0];
codeReader.decodeFromImage(img)
.then(result => {
console.log(result);
resultEl.textContent = result.text;
})
.catch(err => {
console.error(err);
resultEl.textContent = err;
});
console.log(`Started decode for image from ${img.src}`)
};
for (const element of document.getElementsByClassName('decodeButton')) {
element.addEventListener('click', decodeFun, false);
}
})
```
--------------------------------
### Configure Scan Performance
Source: https://context7.com/zxing-js/library/llms.txt
Adjust timing intervals for decoding attempts and manage scanner lifecycle to release camera resources.
```javascript
import { BrowserQRCodeReader } from '@zxing/library';
// Set time between successful scans (default: 500ms)
const codeReader = new BrowserQRCodeReader(1000); // 1 second between scans
// Adjust time between decoding attempts (for failed attempts)
codeReader.timeBetweenDecodingAttempts = 100; // Check every 100ms
// For battery-saving mode, increase delay
codeReader.timeBetweenDecodingAttempts = 500; // Check every 500ms
// Stop scanning methods
codeReader.stopAsyncDecode(); // Stop one-time decode
codeReader.stopContinuousDecode(); // Stop continuous decode
codeReader.reset(); // Full reset, releases camera
```
--------------------------------
### Implement QR code decoding logic
Source: https://github.com/zxing-js/library/blob/master/docs/examples/qr-camera/index.html
Functions for handling single-shot and continuous decoding from a video input device.
```javascript
function decodeOnce(codeReader, selectedDeviceId) { codeReader.decodeFromInputVideoDevice(selectedDeviceId, 'video').then((result) => { console.log(result) document.getElementById('result').textContent = result.text }).catch((err) => { console.error(err) document.getElementById('result').textContent = err }) } function decodeContinuously(codeReader, selectedDeviceId) { codeReader.decodeFromInputVideoDeviceContinuously(selectedDeviceId, 'video', (result, err) => { if (result) { // properly decoded qr code console.log('Found QR code!', result) document.getElementById('result').textContent = result.text } if (err) { // As long as this error belongs into one of the following categories // the code reader is going to continue as excepted. Any other error // will stop the decoding loop. // // Excepted Exceptions: // // - NotFoundException // - ChecksumException // - FormatException if (err instanceof ZXing.NotFoundException) { console.log('No QR code found.') } if (err instanceof ZXing.ChecksumException) { console.log('A code was found, but it\'s read value was not valid.') } if (err instanceof ZXing.FormatException) { console.log('A code was found, but it was in a invalid format.') } } }) } window.addEventListener('load', function () { let selectedDeviceId; const codeReader = new ZXing.BrowserQRCodeReader() console.log('ZXing code reader initialized') codeReader.getVideoInputDevices() .then((videoInputDevices) => { const sourceSelect = document.getElementById('sourceSelect') selectedDeviceId = videoInputDevices[0].deviceId if (videoInputDevices.length >= 1) { videoInputDevices.forEach((element) => { const sourceOption = document.createElement('option') sourceOption.text = element.label sourceOption.value = element.deviceId sourceSelect.appendChild(sourceOption) }) sourceSelect.onchange = () => { selectedDeviceId = sourceSelect.value; }; const sourceSelectPanel = document.getElementById('sourceSelectPanel') sourceSelectPanel.style.display = 'block' } document.getElementById('startButton').addEventListener('click', () => { const decodingStyle = document.getElementById('decoding-style').value; if (decodingStyle == "once") { decodeOnce(codeReader, selectedDeviceId); } else { decodeContinuously(codeReader, selectedDeviceId); } console.log(`Started decode from camera with id ${selectedDeviceId}`) }) document.getElementById('resetButton').addEventListener('click', () => { codeReader.reset() document.getElementById('result').textContent = ''; console.log('Reset.') }) }) .catch((err) => { console.error(err) }) })
```
--------------------------------
### Decode Data Matrix from Image with ZXing
Source: https://github.com/zxing-js/library/blob/master/docs/examples/datamatrix-image/index.html
Initializes the ZXing code reader and sets up event listeners to decode Data Matrix barcodes from images when a button is clicked. It decodes from an `
` element and displays the result or any errors.
```typescript
window.addEventListener('load', function () {
const codeReader = new ZXing.BrowserDatamatrixCodeReader()
console.log('ZXing code reader initialized');
const decodeFun = (e) => {
const parent = e.target.parentNode.parentNode;
const img = parent.getElementsByClassName('img')[0].cloneNode(true);
const resultEl = parent.getElementsByClassName('result')[0];
codeReader.decodeFromImage(img)
.then(result => {
console.log(result);
resultEl.textContent = result.text;
})
.catch(err => {
console.error(err);
resultEl.textContent = err;
});
console.log(`Started decode for image from ${img.src}`)
};
for (const element of document.getElementsByClassName('decodeButton')) {
element.addEventListener('click', decodeFun, false);
}
})
```
--------------------------------
### Decode QR Code from Image using ZXing TypeScript
Source: https://github.com/zxing-js/library/blob/master/docs/examples/qr-image/index.html
Use this code to initialize the ZXing QR code reader and decode a QR code from an image element. Ensure the image element is loaded before attempting to decode. Errors during decoding will be logged to the console and displayed.
```typescript
window.addEventListener('load', function () {
const codeReader = new ZXing.BrowserQRCodeReader()
console.log('ZXing code reader initialized')
document.getElementById('decodeButton').addEventListener('click', () => {
const img = document.getElementById('img')
codeReader.decodeFromImage(img).then((result) => {
console.log(result)
document.getElementById('result').textContent = result.text
}).catch((err) => {
console.error(err)
document.getElementById('result').textContent = err
})
console.log(`Started decode for image from ${img.src}`)
})
})
```
--------------------------------
### Decode PDF 417 from Image with ZXing TypeScript
Source: https://github.com/zxing-js/library/blob/master/docs/examples/pdf417-image/index.html
Initializes the ZXing PDF 417 reader and sets up event listeners to decode barcodes from images when a button is clicked. Ensure the ZXing library is loaded before this script runs.
```typescript
window.addEventListener('load', function () {
const codeReader = new ZXing.BrowserPDF417Reader()
console.log('ZXing code reader initialized');
const decodeFun = (e) => {
const parent = e.target.parentNode.parentNode;
const img = parent.getElementsByClassName('img')[0].cloneNode(true);
const resultEl = parent.getElementsByClassName('result')[0]
codeReader.decodeFromImage(img)
.then(result => {
console.log(result);
resultEl.textContent = result.text;
})
.catch(err => {
console.error(err);
resultEl.textContent = err;
});
console.log(`Started decode for image from ${img.src}`)
};
for (const element of document.getElementsByClassName('decodeButton')) {
element.addEventListener('click', decodeFun, false);
}
})
```
--------------------------------
### Decode Barcodes with MultiFormatReader
Source: https://github.com/zxing-js/library/blob/master/README.md
Initializes a barcode reader with specific format hints and processes image data using a HybridBinarizer.
```javascript
// use with commonJS
const { MultiFormatReader, BarcodeFormat } = require('@zxing/library');
// or with ES6 modules
import { MultiFormatReader, BarcodeFormat } from '@zxing/library';
const hints = new Map();
const formats = [BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX/*, ...*/];
hints.set(DecodeHintType.POSSIBLE_FORMATS, formats);
const reader = new MultiFormatReader();
const luminanceSource = new RGBLuminanceSource(imgByteArray, imgWidth, imgHeight);
const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
reader.decode(binaryBitmap, hints);
```
--------------------------------
### Java to TypeScript Type Mapping
Source: https://github.com/zxing-js/library/blob/master/CONTRIBUTING.md
A cheat sheet for common Java array types and their corresponding TypeScript TypedArray equivalents.
```markdown
| Java | TypeScript |
| -------- | ------------------- |
| `byte[]` | `Uint8ClampedArray` |
| `int[]` | `Int32Array` |
```
--------------------------------
### String Decoding with Encoding
Source: https://github.com/zxing-js/library/blob/master/CONTRIBUTING.md
Illustrates how Java's String constructor for byte arrays with encoding is handled in TypeScript using the StringEncoding utility class.
```typescript
StringEncoding.decode(, encoding)
```
--------------------------------
### Decode Barcodes with MultiFormatReader
Source: https://context7.com/zxing-js/library/llms.txt
Use MultiFormatReader for custom image processing pipelines. Configure hints to specify possible formats and enable advanced decoding. Requires RGBLuminanceSource, BinaryBitmap, and HybridBinarizer for converting image data.
```javascript
import {
MultiFormatReader,
BarcodeFormat,
DecodeHintType,
RGBLuminanceSource,
BinaryBitmap,
HybridBinarizer
} from '@zxing/library';
// Configure the reader with hints
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, [BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX]);
hints.set(DecodeHintType.TRY_HARDER, true);
const reader = new MultiFormatReader();
reader.setHints(hints);
// Decode from raw pixel data (e.g., from canvas)
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Convert RGBA to luminance
const luminanceSource = new RGBLuminanceSource(
new Uint8ClampedArray(imageData.data.buffer),
canvas.width,
canvas.height
);
const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
try {
const result = reader.decodeWithState(binaryBitmap);
console.log('Decoded:', result.getText());
console.log('Format:', BarcodeFormat[result.getBarcodeFormat()]);
} catch (e) {
console.log('No barcode found');
} finally {
reader.reset();
}
```
--------------------------------
### Encode Barcodes with MultiFormatWriter
Source: https://context7.com/zxing-js/library/llms.txt
Generate barcode images as BitMatrix using MultiFormatWriter. Configure encoding hints for margin and error correction. The generated BitMatrix can then be rendered to a canvas.
```javascript
import { MultiFormatWriter, BarcodeFormat, EncodeHintType } from '@zxing/library';
const writer = new MultiFormatWriter();
const hints = new Map();
hints.set(EncodeHintType.MARGIN, 4);
hints.set(EncodeHintType.ERROR_CORRECTION, 'M');
// Generate QR code as BitMatrix
const bitMatrix = writer.encode(
'Hello from ZXing!',
BarcodeFormat.QR_CODE,
300,
300,
hints
);
// Render to canvas
const canvas = document.createElement('canvas');
canvas.width = bitMatrix.getWidth();
canvas.height = bitMatrix.getHeight();
const ctx = canvas.getContext('2d');
for (let y = 0; y < bitMatrix.getHeight(); y++) {
for (let x = 0; x < bitMatrix.getWidth(); x++) {
ctx.fillStyle = bitMatrix.get(x, y) ? '#000000' : '#FFFFFF';
ctx.fillRect(x, y, 1, 1);
}
}
document.body.appendChild(canvas);
```
--------------------------------
### Generate QR codes with BrowserQRCodeSvgWriter
Source: https://context7.com/zxing-js/library/llms.txt
Generates QR codes as SVG elements. Supports custom error correction levels, margins, and direct DOM injection.
```javascript
import { BrowserQRCodeSvgWriter, EncodeHintType } from '@zxing/library';
const writer = new BrowserQRCodeSvgWriter();
// Generate QR code with default settings
const svgElement = writer.write('https://example.com', 300, 300);
document.getElementById('qrcode-container').appendChild(svgElement);
// Generate with custom hints
const hints = new Map();
hints.set(EncodeHintType.ERROR_CORRECTION, 'H'); // Highest error correction
hints.set(EncodeHintType.MARGIN, 2); // Smaller quiet zone
const customSvg = writer.write('Hello World!', 250, 250, hints);
// Write directly to DOM element
writer.writeToDom('#result-container', 'Encoded content here', 200, 200, hints);
```
--------------------------------
### Scan multiple barcode formats with BrowserMultiFormatReader
Source: https://context7.com/zxing-js/library/llms.txt
Use this reader to automatically detect and decode various barcode types. Requires providing format hints for optimal performance.
```javascript
import { BrowserMultiFormatReader, BarcodeFormat, DecodeHintType } from '@zxing/library';
// Create reader with format hints for faster scanning
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
BarcodeFormat.QR_CODE,
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.EAN_13,
BarcodeFormat.CODE_128
]);
const codeReader = new BrowserMultiFormatReader(hints);
// Get available cameras
const devices = await codeReader.listVideoInputDevices();
// Start scanning with continuous callback
codeReader.decodeFromVideoDevice(devices[0].deviceId, 'video', (result, err) => {
if (result) {
console.log('Format:', BarcodeFormat[result.getBarcodeFormat()]);
console.log('Content:', result.getText());
console.log('Timestamp:', result.getTimestamp());
}
if (err && !(err instanceof ZXing.NotFoundException)) {
console.error(err);
}
});
// Reset when finished
codeReader.reset();
```
--------------------------------
### Access BarcodeFormat Constants
Source: https://context7.com/zxing-js/library/llms.txt
Use these constants to specify supported barcode formats for reading or writing operations.
```javascript
import { BarcodeFormat } from '@zxing/library';
// 2D Barcode Formats
BarcodeFormat.QR_CODE // QR Code
BarcodeFormat.DATA_MATRIX // Data Matrix
BarcodeFormat.AZTEC // Aztec
BarcodeFormat.PDF_417 // PDF 417
// 1D Product Barcodes
BarcodeFormat.UPC_A // UPC-A
BarcodeFormat.UPC_E // UPC-E
BarcodeFormat.EAN_8 // EAN-8
BarcodeFormat.EAN_13 // EAN-13
// 1D Industrial Barcodes
BarcodeFormat.CODE_39 // Code 39
BarcodeFormat.CODE_93 // Code 93
BarcodeFormat.CODE_128 // Code 128
BarcodeFormat.CODABAR // Codabar
BarcodeFormat.ITF // Interleaved 2 of 5
BarcodeFormat.RSS_14 // RSS 14
BarcodeFormat.RSS_EXPANDED // RSS Expanded
```
--------------------------------
### Decode from Video Device with ZXing TypeScript
Source: https://github.com/zxing-js/library/blob/master/docs/examples/multi-camera/index.html
Use this code to continuously decode barcodes from a video device. Ensure the ZXing library is loaded and a video element with the ID 'video' exists in your HTML. It handles device selection and displays results or errors.
```typescript
window.addEventListener('load', function () {
let selectedDeviceId;
const codeReader = new ZXing.BrowserMultiFormatReader()
console.log('ZXing code reader initialized')
codeReader.listVideoInputDevices()
.then((videoInputDevices) => {
const sourceSelect = document.getElementById('sourceSelect')
selectedDeviceId = videoInputDevices[0].deviceId
if (videoInputDevices.length >= 1) {
videoInputDevices.forEach((element) => {
const sourceOption = document.createElement('option')
sourceOption.text = element.label
sourceOption.value = element.deviceId
sourceSelect.appendChild(sourceOption)
})
sourceSelect.onchange = () => {
selectedDeviceId = sourceSelect.value;
};
const sourceSelectPanel = document.getElementById('sourceSelectPanel')
sourceSelectPanel.style.display = 'block'
}
document.getElementById('startButton').addEventListener('click', () => {
codeReader.decodeFromVideoDevice(selectedDeviceId, 'video', (result, err) => {
if (result) {
console.log(result)
document.getElementById('result').textContent = result.text
}
if (err && !(err instanceof ZXing.NotFoundException)) {
console.error(err)
document.getElementById('result').textContent = err
}
})
console.log(`Started continous decode from camera with id ${selectedDeviceId}`)
})
document.getElementById('resetButton').addEventListener('click', () => {
codeReader.reset()
document.getElementById('result').textContent = '';
console.log('Reset.')
})
})
.catch((err) => {
console.error(err)
})
})
```
--------------------------------
### Transform Java Numeric Array Initialization to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Converts Java array initialization syntax for numeric types (e.g., `new int[size]`) to TypeScript's `Int32Array` or generic `Array`.
```regex
Search: `new int\[(\w+)\]`
Replace: `new Int32Array($1)`
```
```regex
Search: `new int\[(\w+)\]`
Replace: `new Array($1)`
```
--------------------------------
### Decode QR Code from Image URL with BrowserQRCodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Decodes a QR code directly from an image URL. This method fetches the image and processes it. Handles potential network or decoding errors.
```javascript
import { BrowserQRCodeReader } from '@zxing/library';
const codeReader = new BrowserQRCodeReader();
// Decode from an image URL directly
try {
const result = await codeReader.decodeFromImageUrl('https://example.com/qrcode.png');
console.log('Decoded from URL:', result.getText());
} catch (err) {
console.error('Failed to decode from URL:', err);
}
```
--------------------------------
### Decode QR Code from Image Element with BrowserQRCodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Decodes a QR code from an HTML image element. Ensure the image element is loaded and accessible. Handles potential decoding errors.
```javascript
import { BrowserQRCodeReader } from '@zxing/library';
const codeReader = new BrowserQRCodeReader();
// Decode from an img element
const imgElement = document.getElementById('qrcode-image');
try {
const result = await codeReader.decodeFromImage(imgElement);
console.log('Decoded:', result.getText());
} catch (err) {
console.error('No QR code found in image');
}
```
--------------------------------
### Convert Java 'for-each' to TS 'for-of'
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Changes Java's enhanced for loop syntax to TypeScript's `for...of` loop.
```regex
Search: `for\s*\((.*) (\w+) :`
Replace: `for (const $2/*: $1*/ of`
```
--------------------------------
### Decode barcode from image element
Source: https://github.com/zxing-js/library/blob/master/docs/examples/multi-image/index.html
Initializes the BrowserMultiFormatReader and attaches a click event listener to trigger decoding from an image source.
```javascript
window.addEventListener('load', function () { const codeReader = new ZXing.BrowserMultiFormatReader() console.log('ZXing code reader initialized') document.getElementById('decodeButton').addEventListener('click', () => { const img = document.getElementById('img') codeReader.decodeFromImage(img).then((result) => { console.log(result) document.getElementById('result').textContent = result.text }).catch((err) => { console.error(err) document.getElementById('result').textContent = err }) console.log(`Started decode for image from ${img.src}`) }) })
```
--------------------------------
### Transform Java Variable Declarations to TS (with assignment)
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Converts Java variable declarations with initial assignments (e.g., `type name = value;`) to TypeScript `let` declarations.
```regex
Search: `^(\s*)([\w\[\]]+) (\w+) =`
Replace: `$1let $3: $2 =`
```
--------------------------------
### Scan 1D barcodes with BrowserBarcodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Dedicated reader for 1D barcode formats. Supports TRY_HARDER hint to improve detection accuracy.
```javascript
import { BrowserBarcodeReader, DecodeHintType, BarcodeFormat } from '@zxing/library';
// Create reader with specific format hints
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
BarcodeFormat.EAN_13,
BarcodeFormat.EAN_8,
BarcodeFormat.UPC_A,
BarcodeFormat.CODE_128
]);
hints.set(DecodeHintType.TRY_HARDER, true);
const barcodeReader = new BrowserBarcodeReader(500, hints);
// Scan from video device
const devices = await barcodeReader.listVideoInputDevices();
barcodeReader.decodeFromVideoDevice(devices[0].deviceId, 'video', (result, err) => {
if (result) {
console.log('Product barcode:', result.getText());
// EAN-13 result: "5901234123457"
}
});
```
--------------------------------
### Configure Decoder Behavior with DecodeHintType
Source: https://context7.com/zxing-js/library/llms.txt
Use DecodeHintType to configure decoder behavior for optimized scanning. Options include limiting barcode formats, enabling more accurate but slower decoding, specifying character encoding, and enabling format-specific features like check digit verification or extended modes.
```javascript
import { DecodeHintType, BarcodeFormat } from '@zxing/library';
const hints = new Map();
// Limit to specific barcode formats (improves speed)
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
BarcodeFormat.QR_CODE,
BarcodeFormat.EAN_13,
BarcodeFormat.CODE_128
]);
// Try harder to find barcodes (slower but more accurate)
hints.set(DecodeHintType.TRY_HARDER, true);
// Specify character encoding
hints.set(DecodeHintType.CHARACTER_SET, 'UTF-8');
// For Code 39: enable check digit verification
hints.set(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT, true);
// For Code 39: enable extended mode
hints.set(DecodeHintType.ENABLE_CODE_39_EXTENDED_MODE, true);
// Process as GS1 barcode
hints.set(DecodeHintType.ASSUME_GS1, true);
// For Codabar: return start/end characters
hints.set(DecodeHintType.RETURN_CODABAR_START_END, true);
// Require UPC/EAN extension of specific length
hints.set(DecodeHintType.ALLOWED_EAN_EXTENSIONS, [2, 5]);
```
--------------------------------
### Convert Java Function Signatures to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Transforms Java method signatures, including access modifiers and return types, into a TypeScript format.
```regex
Search: `((private|public|static)( static)?) ([\w\[\]]+) (\w+\(.*?\))`
Replace: `$1 $5: $4`
```
--------------------------------
### Convert Multiple Parameters in Java Method to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Transforms multiple parameter declarations in a Java method signature to TypeScript syntax. Use with caution.
```regex
Search: `(\w+) (\w+)(, |\))`
Replace: `$2: $1$3`
```
--------------------------------
### Transform Java Variable Declarations to TS (without assignment)
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Converts Java variable declarations without initial assignments (e.g., `type name;`) to TypeScript `let` declarations. Use with caution.
```regex
Search: `^(\s*)([\w\[\]]+) (\w+);`
Replace: `$1let $3: $2;`
```
--------------------------------
### URI Result Handler in Java
Source: https://github.com/zxing-js/library/blob/master/src/test/resources/blackbox/aztec-2/22.txt
This Java code handles URI results within the ZXing Android client. It's part of the library's Android integration.
```java
package com.google.zxing.client.android.result;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.util.Log;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.client.result.URIParsedResult;
/**
* Handles "URI" (Uniform Resource Identifier) results.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class URIResultHandler extends ResultHandler {
private static final String TAG = URIResultHandler.class.getSimpleName();
private static final int MATH”; // For example, "http://www.google.com/search?q=math"
public URIResultHandler(Activity activity, ParsedResult result) {
super(activity, result);
}
@Override
public CharSequence getDisplayContents() {
return massage ترمينال "http://www.google.com/search?q=math"
}
@Override
public void handleProductSearch() {
openProductSearch(ResultParser.parseResult(getResult()).getDisplayResult());
}
@Override
public void handleShoppingProductSearch() {
openShoppingProductSearch(ResultParser.parseResult(getResult()).getDisplayResult());
}
@Override
public int getDisplayTitle() {
return R.string.result_uri;
}
}
```
--------------------------------
### Convert Java 'for' loop to TS 'for' loop
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Refactors basic Java `for` loop declarations to TypeScript's `for` loop syntax, using `let` for the loop variable.
```regex
Search: `for\s*\((\w+) (\w+)`
Replace: `for (let $2 /*$1*/`
```
--------------------------------
### Normalize Equals Comparison Operators
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Standardizes inequality and equality comparison operators by appending an equals sign.
```regex
Search: `(!=|==)`
Replace: `$1=`
```
--------------------------------
### Convert Function Signatures without Accessors to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Converts function signatures that lack explicit access modifiers into TypeScript format. Use with caution.
```regex
Search: `([\w\[\]]+) (\w+\(.*?\))`
Replace: `$2: $1`
```
--------------------------------
### Scan Aztec codes with BrowserAztecCodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Reader for Aztec 2D barcodes. Useful for transportation tickets and similar applications.
```javascript
import { BrowserAztecCodeReader } from '@zxing/library';
const aztecReader = new BrowserAztecCodeReader();
// Scan Aztec codes from camera
aztecReader.decodeFromVideoDevice(null, 'video', (result, err) => {
if (result) {
console.log('Aztec code content:', result.getText());
}
});
```
--------------------------------
### Decode Data Matrix with BrowserDatamatrixCodeReader
Source: https://context7.com/zxing-js/library/llms.txt
Specialized reader for industrial Data Matrix 2D barcodes. Supports decoding directly from image elements.
```javascript
import { BrowserDatamatrixCodeReader } from '@zxing/library';
const dmReader = new BrowserDatamatrixCodeReader();
// Decode Data Matrix from image
const result = await dmReader.decodeFromImage('datamatrix-element');
console.log('Data Matrix content:', result.getText());
console.log('Raw bytes:', result.getRawBytes());
```
--------------------------------
### Access Decoded Barcode Data with Result Object
Source: https://context7.com/zxing-js/library/llms.txt
The Result object provides access to decoded barcode information, including text content, raw bytes, format, corner points, timestamp, and metadata. This is typically obtained after a successful decoding operation.
```javascript
// After successful decoding
const result = await codeReader.decodeOnceFromVideoDevice(deviceId, 'video');
// Get the decoded text content
const text = result.getText();
console.log('Content:', text);
// Get raw bytes (for binary data)
const rawBytes = result.getRawBytes();
console.log('Raw bytes length:', rawBytes ? rawBytes.length : 0);
// Get the barcode format
const format = result.getBarcodeFormat();
console.log('Format:', format); // Numeric enum value
// Get result points (corner positions)
const points = result.getResultPoints();
points.forEach((point, i) => {
console.log(`Point ${i}: (${point.getX()}, ${point.getY()})`);
});
// Get decode timestamp
const timestamp = result.getTimestamp();
console.log('Decoded at:', new Date(timestamp));
// Get metadata (orientation, error correction level, etc.)
const metadata = result.getResultMetadata();
if (metadata) {
metadata.forEach((value, key) => {
console.log(`Metadata ${key}:`, value);
});
}
```
--------------------------------
### Refactor Java 'final' Props to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Transforms Java property declarations with `final` keywords into TypeScript syntax. Use with caution.
```regex
Search: `((private|public|static)( static)?) final ([\w\[\]]+) (\w+)( =|;)`
Replace: `$1 /*final*/ $5: $4$6`
```
--------------------------------
### Convert Single Parameter in Java Method to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Refactors a single parameter declaration within parentheses in a Java method signature to TypeScript syntax.
```regex
Search: `\((([\w\[\]]+) (\w+)(\,)?)+\)`
Replace: `($3: $2$4)`
```
--------------------------------
### Transform Java Type Casts to TS
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Converts Java-style type casting (e.g., `(int) variable`) to TypeScript's type assertion syntax (e.g., `variable`).
```regex
Search: `\((float|int|byte|short|long|char)\)\s*(\w+)`
Replace: `<$1>$2`
```
--------------------------------
### Transform Array Declaration (Java to TS)
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Converts Java-style array declarations like `int[]` to TypeScript's `Int32Array`.
```regex
Search: `int\[\]`
Replace: `Int32Array`
```
--------------------------------
### Convert Java Numeric Types to TS 'number'
Source: https://github.com/zxing-js/library/blob/master/HELPER_REGEX.md
Replaces Java primitive numeric types (byte, short, int, float, long) and their array equivalents with TypeScript's `number` type.
```regex
Search: `: (byte|short|int|float|long)(\[\])?`
Replace: `: /*$1$2*/ number$2`
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.