### Install zxing-wasm Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Install the zxing-wasm package using npm. ```bash npm i zxing-wasm ``` -------------------------------- ### Build zxing-wasm Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Steps to clone the repository, install dependencies using pnpm, and build the WASM module. Requires pnpm, CMake, and Emscripten. ```bash git clone --recurse-submodules https://github.com/Sec-ant/zxing-wasm cd zxing-wasm # Install pnpm before executing the next command: # https://pnpm.io/installation pnpm i --frozen-lockfile # Install CMake before executing the next command: # https://cmake.org/download/ # Install Emscripten before executing the next command: # https://emscripten.org/docs/getting_started/downloads.html pnpm build:wasm pnpm build ``` -------------------------------- ### Read Barcodes from ImageData Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Demonstrates reading barcodes from `ImageData` using `readBarcodes`. This involves creating an `ImageBitmap` and then drawing it onto an `OffscreenCanvas` to get the `ImageData`. Options are similar to reading from files/blobs. ```typescript /** * Read from image data */ const imageData = await createImageBitmap(imageFile).then((imageBitmap) => { const { width, height } = imageBitmap; const context = new OffscreenCanvas(width, height).getContext( "2d", ) as OffscreenCanvasRenderingContext2D; context.drawImage(imageBitmap, 0, 0, width, height); return context.getImageData(0, 0, width, height); }); const imageDataReadResults = await readBarcodes(imageData, readerOptions); console.log(imageDataReadResults[0].text); // Hello world! console.log(imageDataReadResults[0].format); // QRCode console.log(imageDataReadResults[0].symbology); // QRCode ``` -------------------------------- ### Import ZXING_WASM_SHA256 in TypeScript Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import the ZXING_WASM_SHA256 variable to get the SHA-256 hash of the .wasm file for integrity checks. ```typescript import { ZXING_WASM_SHA256 } from "zxing-wasm"; ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Run this command in the root of the repository to initialize and update all required git submodules if they were not cloned initially. ```bash git submodule update --init --recursive ``` -------------------------------- ### Prepare ZXing Module for WeChat Mini Programs Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Configure zxing-wasm for WeChat mini programs using `WXWebAssembly.instantiate`. Ensure the `zxing_full.wasm` file is copied into the project directory and use the correct path in the instantiation call. ```typescript prepareZXingModule({ overrides: { instantiateWasm(imports, successCallback) { WXWebAssembly.instantiate("path/to/zxing_full.wasm", imports).then( ({ instance }) => successCallback(instance), ); return {}; }, }, }); ``` -------------------------------- ### Configure and Pre-load WASM Module with prepareZXingModule Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Manages the loading and instantiation of the zxing WASM module. Allows overriding the WASM source, eagerly loading the module, or forcing a re-fetch. Useful for self-hosting WASM or in Node.js environments. ```typescript import { prepareZXingModule, readBarcodes, ZXING_WASM_VERSION, } from "zxing-wasm"; // --- Override WASM source (e.g. self-host on unpkg) --- prepareZXingModule({ overrides: { locateFile: (path, prefix) => { if (path.endsWith(".wasm")) { return `https://unpkg.com/zxing-wasm@${ZXING_WASM_VERSION}/dist/full/${path}`; } return prefix + path; }, }, // fireImmediately: false (default) — only updates config, defers load }); // --- Eager pre-load and await instantiation --- await prepareZXingModule({ overrides: { /* custom locateFile */ }, fireImmediately: true, // returns Promise }); // readBarcodes will now reuse the cached module instantly const results = await readBarcodes(imageBlob); // --- Force re-fetch (e.g. after config change) --- prepareZXingModule({ overrides: { locateFile: (p, pfx) => pfx + p }, fireImmediately: true, equalityFn: () => false, // bypass cache equality check }); // --- Node.js: serve WASM from local filesystem --- import { readFileSync } from "node:fs"; import { prepareZXingModule } from "zxing-wasm/reader"; prepareZXingModule({ overrides: { instantiateWasm(imports, successCallback) { WebAssembly.instantiate( readFileSync("node_modules/zxing-wasm/dist/reader/zxing_reader.wasm"), imports, ).then(({ instance }) => successCallback(instance)); return {}; }, }, }); ``` -------------------------------- ### Download zxing_full.wasm from CDN Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md URL to download the full zxing_full.wasm file from a CDN. Replace with the desired zxing-wasm version. ```text https://cdn.jsdelivr.net/npm/zxing-wasm@/dist/full/zxing_full.wasm ``` -------------------------------- ### Importing readBarcodes and writeBarcode from zxing-wasm Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md This snippet shows how to import both reading and writing functions from the main 'zxing-wasm' entry point. It is equivalent to importing from '/full'. ```APIDOC ## Import readBarcodes and writeBarcode ### Description Import both `readBarcodes` and `writeBarcode` functions from the main `zxing-wasm` entry point. This is equivalent to using the `zxing-wasm/full` subpath. ### Usage ```ts import { readBarcodes, writeBarcode } from "zxing-wasm"; ``` ``` -------------------------------- ### Prepare ZXing Module with locateFile and Base64 Data URL in Node.js Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Load the WASM file using `Module.locateFile` with a Base64-encoded Data URL. This method is not recommended due to potential performance implications and increased data size. ```typescript import { readFileSync } from "node:fs"; import { prepareZXingModule } from "zxing-wasm/reader"; const wasmBase64 = readFileSync("/path/to/the/zxing_reader.wasm").toString( "base64", ); const wasmUrl = `data:application/wasm;base64,${wasmBase64}`; prepareZXingModule({ overrides: { locateFile: (path, prefix) => { if (path.endsWith(".wasm")) { return wasmUrl; } return prefix + path; }, }, }); ``` -------------------------------- ### Instantiate ZXing Module Immediately Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Set fireImmediately to true to trigger immediate fetching and instantiation of the WASM module. prepareZXingModule will return a Promise that resolves to the Emscripten module. ```typescript prepareZXingModule({ overrides: { /* ... your desired overrides ... */ }, fireImmediately: true, }); // <-- returns a promise ``` -------------------------------- ### prepareZXingModule Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Configures and pre-loads the WebAssembly (WASM) module for ZXing. Allows overriding the WASM source location, eagerly instantiating the module, or forcing a re-fetch. ```APIDOC ## prepareZXingModule(options?) ### Description Controls how and when the underlying Emscripten WASM module is fetched, compiled, and cached. By default, the WASM is loaded lazily on the first `readBarcodes`/`writeBarcode` call. Call `prepareZXingModule` before reading/writing to override the WASM location or to eagerly instantiate it. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object, optional) - Configuration options for module preparation. - **overrides** (object) - Object for overriding WASM loading behavior. - **locateFile** (function) - A function to determine the URL of WASM files. Receives path and prefix, should return the full URL. - **instantiateWasm** (function) - A function to manually instantiate the WASM module. Receives imports and a success callback. - **fireImmediately** (boolean) - If true, eagerly loads and instantiates the module, returning a Promise. Defaults to false. - **equalityFn** (function) - A function to determine if cached module configuration is still valid. Defaults to a strict equality check. ### Request Example ```ts import { prepareZXingModule } from "zxing-wasm"; // Override WASM source prepareZXingModule({ overrides: { locateFile: (path, prefix) => { if (path.endsWith(".wasm")) { return `https://unpkg.com/zxing-wasm@${ZXING_WASM_VERSION}/dist/full/${path}`; } return prefix + path; }, }, }); // Eager pre-load and await instantiation await prepareZXingModule({ fireImmediately: true, }); // Node.js: serve WASM from local filesystem import { readFileSync } from "node:fs"; import { prepareZXingModule } from "zxing-wasm/reader"; prepareZXingModule({ overrides: { instantiateWasm(imports, successCallback) { WebAssembly.instantiate( readFileSync("node_modules/zxing-wasm/dist/reader/zxing_reader.wasm"), imports, ).then(({ instance }) => successCallback(instance)); return {}; }, }, }); ``` ### Response #### Success Response (200) - **Promise** - If `fireImmediately` is true, returns a Promise that resolves with the instantiated ZXingModule. #### Response Example (No direct response example, as it returns a Promise or modifies configuration.) ``` -------------------------------- ### Prepare ZXing Module with instantiateWasm in Node.js Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Use the `Module.instantiateWasm` API to manually instantiate the WebAssembly module. This is useful when you need more control over the instantiation process. Ensure the WASM file is accessible. ```typescript import { readFileSync } from "node:fs"; import { prepareZXingModule } from "zxing-wasm/reader"; const wasmFileBuffer = readFileSync("/path/to/the/zxing_reader.wasm"); prepareZXingModule({ overrides: { instantiateWasm(imports, successCallback) { WebAssembly.instantiate(wasmFileBuffer, imports).then(({ instance }) => successCallback(instance)); return {}; }, }, }); ``` -------------------------------- ### Download zxing_writer.wasm from CDN Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md URL to download the zxing_writer.wasm file from a CDN. Replace with the desired zxing-wasm version. ```text https://cdn.jsdelivr.net/npm/zxing-wasm@/dist/writer/zxing_writer.wasm ``` -------------------------------- ### Prepare ZXing Module with locateFile and Object URL in Node.js Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Use the `Module.locateFile` API with an Object URL to load the WASM file. This approach creates a temporary URL for the WASM file and requires revoking the URL after use to free memory. ```typescript import { readFileSync } from "node:fs"; import { prepareZXingModule } from "zxing-wasm/reader"; // Create an Object URL for the .wasm file. const wasmFileUrl = URL.createObjectURL( new Blob([readFileSync("/path/to/the/zxing_reader.wasm")], { type: "application/wasm", }), ); prepareZXingModule({ overrides: { locateFile: (path, prefix) => { if (path.endsWith(".wasm")) { return wasmFileUrl; } return prefix + path; }, // Call `URL.revokeObjectURL(wasmFileUrl)` after the ZXing module // is fully instantiated to free up memory. postRun: [ () => { URL.revokeObjectURL(wasmFileUrl); }, ], }, }); ``` -------------------------------- ### Download zxing_reader.wasm from CDN Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md URL to download the zxing_reader.wasm file from a CDN. Replace with the desired zxing-wasm version. ```text https://cdn.jsdelivr.net/npm/zxing-wasm@/dist/reader/zxing_reader.wasm ``` -------------------------------- ### Configure Custom CDN Path with locateFile Override Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Use `prepareZXingModule` with an `overrides` object to specify a custom `locateFile` function for fetching the WASM module from a different CDN or server. This is useful for controlling where the WASM binary is loaded from. ```typescript import { prepareZXingModule, writeBarcode, ZXING_WASM_VERSION, } from "zxing-wasm"; // Override the locateFile function prepareZXingModule({ overrides: { locateFile: (path, prefix) => { if (path.endsWith(".wasm")) { return `https://unpkg.com/zxing-wasm@${ZXING_WASM_VERSION}/dist/full/${path}`; } return prefix + path; }, }, }); // Call read or write functions afterward const writeOutput = await writeBarcode("Hello world!"); ``` -------------------------------- ### Import readBarcodes and writeBarcode from zxing-wasm/full Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import functions for both reading and writing barcodes. This path includes the full WASM binary. ```typescript import { readBarcodes, writeBarcode } from "zxing-wasm/full"; ``` -------------------------------- ### Prepare ZXing Module with Overrides Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Call prepareZXingModule with overrides to configure the WASM module. This does not trigger immediate fetching or instantiation. ```typescript prepareZXingModule({ overrides: { /* ... your desired overrides ... */ }, }); // <-- returns void ``` -------------------------------- ### Importing readBarcodes and writeBarcode from zxing-wasm/full Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md This snippet shows how to import both reading and writing functions from the 'full' subpath of the zxing-wasm library. This is suitable when you need both functionalities. ```APIDOC ## Import readBarcodes and writeBarcode ### Description Import both `readBarcodes` and `writeBarcode` functions from the `zxing-wasm/full` subpath. This provides access to all functionalities of the library. ### Usage ```ts import { readBarcodes, writeBarcode } from "zxing-wasm/full"; ``` ``` -------------------------------- ### Prepare ZXing Module with wasmBinary in Node.js Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Configure zxing-wasm to load the WebAssembly module directly from a binary buffer using the `Module.wasmBinary` API. This method requires reading the WASM file into an ArrayBuffer. ```typescript import { readFileSync } from "node:fs"; import { prepareZXingModule } from "zxing-wasm/reader"; prepareZXingModule({ overrides: { wasmBinary: readFileSync("/path/to/the/zxing_reader.wasm") .buffer as ArrayBuffer, }, }); ``` -------------------------------- ### Default jsDelivr CDN locateFile Override Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md This snippet shows the default `locateFile` function configuration used to serve the WASM module via the jsDelivr CDN. It demonstrates how to construct the CDN path based on the WASM file name and version. ```typescript const DEFAULT_MODULE_OVERRIDES: ZXingModuleOverrides = { locateFile: (path, prefix) => { const match = path.match(/_(.+?)\.wasm$/); if (match) { return `https://fastly.jsdelivr.net/npm/zxing-wasm@${ZXING_WASM_VERSION}/${match[1]}/${path}`; } return prefix + path; }, }; ``` -------------------------------- ### IIFE / CDN Script Tag Usage in HTML/JavaScript Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Load the library directly in a browser via a script tag without a bundler. All exports are available under the global `ZXingWASM` object. ```html ``` -------------------------------- ### Importing writeBarcode from zxing-wasm/writer Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md This snippet shows how to import only the barcode writing function from the 'writer' subpath. This is beneficial for minimizing the wasm binary size when reading functionality is not required. ```APIDOC ## Import writeBarcode ### Description Import only the `writeBarcode` function from the `zxing-wasm/writer` subpath. This is recommended if you only need to write barcodes, as it results in a smaller wasm binary size. ### Usage ```ts import { writeBarcode } from "zxing-wasm/writer"; ``` ``` -------------------------------- ### Import readBarcodes and writeBarcode from zxing-wasm Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import functions for both reading and writing barcodes using the main package path. This path includes the full WASM binary. ```typescript import { readBarcodes, writeBarcode } from "zxing-wasm"; ``` -------------------------------- ### Import writeBarcode from zxing-wasm/writer Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import only the function for writing barcodes. This path uses a smaller WASM binary. ```typescript import { writeBarcode } from "zxing-wasm/writer"; ``` -------------------------------- ### Import readBarcodes from zxing-wasm/reader Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import only the function for reading barcodes. This path uses a smaller WASM binary. ```typescript import { readBarcodes } from "zxing-wasm/reader"; ``` -------------------------------- ### Importing readBarcodes from zxing-wasm/reader Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md This snippet demonstrates importing only the barcode reading function from the 'reader' subpath. This is useful for reducing bundle size when writing functionality is not needed. ```APIDOC ## Import readBarcodes ### Description Import only the `readBarcodes` function from the `zxing-wasm/reader` subpath. This is recommended if you only need to read barcodes, as it results in a smaller wasm binary size. ### Usage ```ts import { readBarcodes } from "zxing-wasm/reader"; ``` ``` -------------------------------- ### Read Barcodes from Image File/Blob Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Demonstrates reading barcodes from an image file or blob using `readBarcodes`. Configure reader options such as `tryHarder`, `formats`, and `maxNumberOfSymbols`. The result is a promise resolving to an array of `ReadResult` objects. ```typescript import { readBarcodes, type ReaderOptions } from "zxing-wasm/reader"; const readerOptions: ReaderOptions = { tryHarder: true, formats: ["QRCode"], maxNumberOfSymbols: 1, }; /** * Read from image file/blob */ const imageFile = await fetch( "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Hello%20world!", ).then((resp) => resp.blob()); const imageFileReadResults = await readBarcodes(imageFile, readerOptions); console.log(imageFileReadResults[0].text); // Hello world! console.log(imageFileReadResults[0].format); // QRCode console.log(imageFileReadResults[0].symbology); // QRCode ``` -------------------------------- ### Include IIFE Scripts for ZXing-WASM Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Include these script tags in your HTML to use ZXing-WASM via IIFE. Replace `` with the desired version number. Different scripts are available for full functionality, reader-only, or writer-only. ```html ``` ```html ``` ```html ``` -------------------------------- ### IIFE Scripts Inclusion Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Instructions on how to include the zxing-wasm library using IIFE scripts for different modules (full, reader, writer). ```HTML ``` -------------------------------- ### purgeZXingModule Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Evicts the currently cached WebAssembly (WASM) module, allowing it to be garbage-collected. The module will be re-instantiated on the next read or write operation. ```APIDOC ## purgeZXingModule() ### Description Removes the instantiated module from the internal cache so it can be garbage-collected and will be re-instantiated on the next read/write call. ### Parameters None ### Request Example ```ts import { purgeZXingModule, readBarcodes } from "zxing-wasm"; // Free WASM memory after a batch of operations await readBarcodes(imageBlob); purgeZXingModule(); // Next call to readBarcodes will re-instantiate the module ``` ### Response #### Success Response (200) (This function does not return a value, but performs an action.) #### Response Example (No direct response example, as it performs an action.) ``` -------------------------------- ### Barcode Format Utilities in TypeScript Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Access exported arrays, types, and helper functions for barcode format metadata. Useful for inspecting and converting format names, symbology families, and HRI labels. ```typescript import { BARCODE_FORMATS, BARCODE_SYMBOLOGIES, BARCODE_META_FORMATS, LINEAR_BARCODE_FORMATS, MATRIX_BARCODE_FORMATS, READABLE_BARCODE_FORMATS, CREATABLE_BARCODE_FORMATS, GS1_BARCODE_FORMATS, RETAIL_BARCODE_FORMATS, INDUSTRIAL_BARCODE_FORMATS, BARCODE_HRI_LABELS, symbologyToFormats, formatToSymbology, formatToLabel, } from "zxing-wasm"; // All canonical format names (excludes meta-formats) console.log(BARCODE_FORMATS); // ["Codabar", "Code39", "Code39Std", "Code39Ext", ..., "MaxiCode"] // Meta-formats (logical groupings for ReaderOptions.formats) console.log(BARCODE_META_FORMATS); // ["All", "AllReadable", "AllCreatable", "AllLinear", "AllMatrix", // "AllGS1", "AllRetail", "AllIndustrial"] // Symbology families console.log(BARCODE_SYMBOLOGIES); // ["Codabar", "Code39", "Code93", "Code128", "ITF", "DataBar", // "EANUPC", "OtherBarcode", "PDF417", "Aztec", "QRCode", "DataMatrix", "MaxiCode"] // Format-to-symbology lookup console.log(formatToSymbology("EAN13")); // "EANUPC" console.log(formatToSymbology("MicroQRCode")); // "QRCode" console.log(formatToSymbology("Code39Ext")); // "Code39" // Symbology-to-formats expansion console.log(symbologyToFormats("EANUPC")); // ["EANUPC", "EAN13", "EAN8", "EAN5", "EAN2", "ISBN", "UPCA", "UPCE"] // Human-readable label for a format console.log(formatToLabel("EAN13")); // "EAN-13" console.log(formatToLabel("RMQRCode")); // "rMQR Code" console.log(formatToLabel("PZN")); // "Pharmazentralnummer" // Filter to readable / creatable / GS1-capable subsets console.log(READABLE_BARCODE_FORMATS); // formats that readBarcodes can detect console.log(CREATABLE_BARCODE_FORMATS); // formats that writeBarcode can produce console.log(GS1_BARCODE_FORMATS); // ["Code128", "DataBar", ..., "QRCode", "DataMatrix", "Aztec", "RMQRCode"] console.log(RETAIL_BARCODE_FORMATS); // ["DataBar", ..., "EANUPC", "EAN13", ...] console.log(INDUSTRIAL_BARCODE_FORMATS); // ["Code39", ..., "Code128", "ITF", ...] ``` -------------------------------- ### Import ZXING_WASM_VERSION in TypeScript Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import the ZXING_WASM_VERSION variable to check the resolved version of zxing-wasm in your project. ```typescript import { ZXING_WASM_VERSION } from "zxing-wasm"; ``` -------------------------------- ### Version Constants in TypeScript Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Access string constants for library version, zxing-cpp commit, and WASM binary SHA-256. Useful for integrity checks and constructing CDN URLs. ```typescript import { ZXING_WASM_VERSION, ZXING_CPP_COMMIT, ZXING_WASM_SHA256, } from "zxing-wasm"; // Available from all three subpaths (full, reader, writer) console.log(ZXING_WASM_VERSION); // e.g. "3.0.2" console.log(ZXING_CPP_COMMIT); // e.g. "b304f665..." console.log(ZXING_WASM_SHA256); // SHA-256 hex of the .wasm binary for SRI checks // Construct a CDN URL for the matching WASM binary const wasmUrl = `https://cdn.jsdelivr.net/npm/zxing-wasm@${ZXING_WASM_VERSION}/dist/full/zxing_full.wasm`; // Use in a Subresource Integrity check const link = ``; ``` -------------------------------- ### writeBarcode Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Encodes data into a barcode and returns the result as a Promise. Supports various output formats including SVG, UTF-8 string, PNG Blob, and raw pixel data. Accepts string or Uint8Array input and optional writer options. ```APIDOC ## writeBarcode(input, writerOptions?) ### Description Encodes data into a barcode. Returns a `Promise` containing the barcode as an SVG string, a UTF-8 block-character string, a PNG image `Blob`, and a raw symbol pixel map. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string | Uint8Array) - The data to encode into a barcode. - **writerOptions** (WriterOptions, optional) - Options to configure the barcode writing process. - **format** (string) - The barcode format (e.g., "QRCode", "EAN8", "ISBN"). - **scale** (number) - Module size multiplier. Negative values auto-fit to absolute pixel size. - **rotate** (0 | 90 | 180 | 270) - Rotation of the barcode. - **invert** (boolean) - Invert foreground and background colors. - **addHRT** (boolean) - Add Human Readable Text below the barcode. - **addQuietZones** (boolean) - Add quiet zones around the barcode. - **options** (string) - Symbology-specific options string. ### Request Example ```ts import { writeBarcode, type WriterOptions } from "zxing-wasm/writer"; const options: WriterOptions = { format: "QRCode", scale: 3, rotate: 0, invert: false, addHRT: false, addQuietZones: true, options: "ecLevel=H", }; const result = await writeBarcode("Hello world!", options); console.log(result.svg); console.log(result.utf8); console.log(result.image); console.log(result.symbol); console.log(result.error); ``` ### Response #### Success Response (200) - **svg** (string) - The barcode as an SVG string. - **utf8** (string) - The barcode as a UTF-8 block-character string. - **image** (Blob | null) - The barcode as a PNG image Blob, or null on error. - **symbol** (object | null) - Raw pixel data, width, and height of the barcode symbol. - **data** (Uint8ClampedArray) - Pixel data. - **width** (number) - Width of the symbol. - **height** (number) - Height of the symbol. - **error** (string) - An error message if encoding failed, otherwise an empty string. #### Response Example ```json { "svg": "...", "utf8": " multi-line string using \" \", \"▀\", \"▄\", \"█\"", "image": null, // or a Blob object "symbol": { "data": [ ... ], "width": 100, "height": 100 }, "error": "" } ``` ``` -------------------------------- ### Define DOM-compatible ImageData in Node.js Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md When using zxing-wasm in Node.js or other runtimes, define a DOM-compatible ImageData object with data, width, and height properties. The data should be in RGBA format. ```typescript interface ImageData { data: Uint8ClampedArray; width: number; height: number; } ``` -------------------------------- ### Import ZXING_CPP_COMMIT in TypeScript Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Import the ZXING_CPP_COMMIT variable to access the commit hash of the zxing-cpp submodule. ```typescript import { ZXING_CPP_COMMIT } from "zxing-wasm"; ``` -------------------------------- ### Custom Equality Function for Overrides Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Provide a custom equalityFn to control how overrides are compared for re-fetching and re-instantiating the WASM module. Setting it to () => false forces a re-fetch and re-instantiate. ```typescript prepareZXingModule({ overrides: { /* ... your desired overrides ... */ }, fireImmediately: true, equalityFn: () => false, // <-- force re-fetch and re-instantiate }); ``` -------------------------------- ### Evict Cached WASM Module with purgeZXingModule Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Removes the currently instantiated WASM module from the cache, allowing it to be garbage collected. The module will be re-instantiated on the next read or write operation. ```typescript import { purgeZXingModule } from "zxing-wasm"; // Free WASM memory after a batch of operations await readBarcodes(imageBlob); purgeZXingModule(); // Next call to readBarcodes will re-instantiate the module ``` -------------------------------- ### Encode Data into Barcode with writeBarcode Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Encodes string or Uint8Array data into various barcode formats. Supports customization via WriterOptions for format, scale, rotation, and symbology-specific settings. Returns a Promise with SVG, UTF-8 string, PNG Blob, and raw symbol data. ```typescript import { writeBarcode, type WriterOptions } from "zxing-wasm/writer"; const options: WriterOptions = { format: "QRCode", // default; accepts canonical names, HRI labels, or aliases scale: 3, // module size multiplier (negative = auto-fit to abs(scale) px) rotate: 0, // 0 | 90 | 180 | 270 invert: false, // invert foreground/background colors addHRT: false, // add Human Readable Text below barcode addQuietZones: true, // add quiet zones around barcode (default: true) options: "ecLevel=H", // symbology-specific options string (see below) }; const result = await writeBarcode("Hello world!", options); console.log(result.svg); // '...' console.log(result.utf8); // multi-line string using " ", "▀", "▄", "█" console.log(result.image); // Blob (image/png) or null on error console.log(result.symbol); // { data: Uint8ClampedArray, width: number, height: number } console.log(result.error); // "" on success, error message on failure // Render SVG directly in the browser document.getElementById("barcode")!.innerHTML = result.svg; // Download PNG const url = URL.createObjectURL(result.image!); const a = document.createElement("a"); a.href = url; a.download = "barcode.png"; a.click(); // --- Various formats --- await writeBarcode("12345678", { format: "EAN8" }); await writeBarcode("978-3-16-148410-0", { format: "ISBN" }); await writeBarcode("Hello", { format: "DataMatrix", options: "forceSquare" }); await writeBarcode("GS1 data", { format: "Code128", options: "gs1" }); await writeBarcode("PDF content", { format: "PDF417", options: "columns=3,rows=10", }); // --- Binary (Uint8Array) input --- const binaryData = new Uint8Array([0x01, 0x02, 0x03, 0xff]); const binResult = await writeBarcode(binaryData, { format: "QRCode" }); ``` -------------------------------- ### writeBarcode Function Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Details on the `writeBarcode` function, which encodes text or bytes into a barcode using specified writer options. It returns a Promise resolving to a WriteResult object. ```APIDOC ## writeBarcode ### Description Encodes a given text string or `Uint8Array` into a barcode with optional `WriterOptions`. Returns a Promise of a `WriteResult`. ### Method `writeBarcode(data: string | Uint8Array, options?: WriterOptions): Promise" ### Parameters #### Arguments - **data**: The data to encode. Can be a string or a `Uint8Array`. - **options** (optional): An object conforming to the `WriterOptions` interface to customize barcode generation. ### Request Example ```ts import { writeBarcode, type WriterOptions } from "zxing-wasm/writer"; const writerOptions: WriterOptions = { format: "QRCode", scale: 3, // options: "ecLevel=H", // symbology-specific options string // addHRT: true, // add human readable text // addQuietZones: true, // add quiet zones (default) // invert: false, // invert colors }; const writeOutput = await writeBarcode("Hello world!", writerOptions); console.log(writeOutput.svg); console.log(writeOutput.utf8); console.log(writeOutput.image); console.log(writeOutput.symbol); ``` ### Response #### Success Response A `Promise` that resolves to a `WriteResult` object containing the generated barcode in various formats. #### `WriteResult` Interface - **svg** (string): An SVG string representation of the barcode. - **utf8** (string): A multi-line string representation using block characters. - **image** (Blob): A PNG image Blob of the barcode. - **symbol** ({ data: Uint8ClampedArray, width: number, height: number }): Raw image data and dimensions. ``` -------------------------------- ### Decode Barcodes from ImageData, ArrayBuffer, or Node.js Buffer Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Demonstrates reading barcodes from various image data types including `ImageData` (from canvas), `ArrayBuffer`, and `Uint8Array` (used in Node.js). This snippet highlights the flexibility of the `readBarcodes` function in handling different input formats. ```typescript // --- from ImageData (e.g. canvas) --- const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d")!; const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const imgResults = await readBarcodes(imageData, { formats: ["EAN13", "UPCA"] }); // --- from ArrayBuffer --- const buffer = await imageBlob.arrayBuffer(); const bufResults = await readBarcodes(buffer); // --- in Node.js (no DOM ImageData needed — duck-typed) --- import { readFile } from "node:fs/promises"; const pngBuffer = await readFile("barcode.png"); const nodeResults = await readBarcodes(pngBuffer); // Uint8Array accepted directly ``` -------------------------------- ### Write Barcode with ZXing-WASM Source: https://github.com/sec-ant/zxing-wasm/blob/main/README.md Encodes text or bytes into a barcode using `writeBarcode`. Supports various writer options like `format`, `scale`, and symbology-specific options. The function returns a promise with the barcode data in different formats (SVG, UTF8 string, PNG blob, or raw symbol data). ```typescript import { writeBarcode, type WriterOptions } from "zxing-wasm/writer"; const writerOptions: WriterOptions = { format: "QRCode", scale: 3, // options: "ecLevel=H", // symbology-specific options string // addHRT: true, // add human readable text // addQuietZones: true, // add quiet zones (default) // invert: false, // invert colors }; const writeOutput = await writeBarcode("Hello world!", writerOptions); console.log(writeOutput.svg); // An SVG string. console.log(writeOutput.utf8); // A multi-line string made up of " ", "▀", "▄", "█" characters. console.log(writeOutput.image); // A PNG image blob. console.log(writeOutput.symbol); // { data: Uint8ClampedArray, width: number, height: number } ``` -------------------------------- ### Decode Barcodes from Image Blob Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Reads barcodes from a Blob object, such as an image fetched from a URL. Allows detailed configuration of reader options for accuracy and format filtering. Requires importing `readBarcodes` and `ReaderOptions` from 'zxing-wasm/reader'. ```typescript import { readBarcodes, type ReaderOptions } from "zxing-wasm/reader"; // --- from a URL (Blob) --- const imageBlob = await fetch( "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=Hello%20world!", ).then((r) => r.blob()); const options: ReaderOptions = { formats: ["QRCode"], // restrict to QR codes; [] = all formats tryHarder: true, // optimize for accuracy (default: true) tryRotate: true, // try 90/180/270° rotations (default: true) tryInvert: true, // try inverted reflectance (default: true) tryDownscale: true, // downscale large images (default: true) maxNumberOfSymbols: 5, // cap results (default: 255; 0 = unlimited) binarizer: "LocalAverage", // "LocalAverage"|"GlobalHistogram"|"FixedThreshold"|"BoolCast" textMode: "HRI", // "Plain"|"ECI"|"HRI"|"Hex"|"HexECI"|"Escaped" eanAddOnSymbol: "Ignore", // "Ignore"|"Read"|"Require" characterSet: "Unknown", // auto-detect; or specify e.g. "UTF8" returnErrors: false, // include results with checksum errors isPure: false, // true = single perfectly-aligned barcode image }; const results = await readBarcodes(imageBlob, options); for (const result of results) { if (!result.isValid) { console.error("Failed:", result.error); continue; } console.log(result.text); // "Hello world!" console.log(result.format); // "QRCode" console.log(result.symbology); // "QRCode" console.log(result.contentType); // "Text" | "Binary" | "Mixed" | "GS1" | ... console.log(result.orientation); // rotation in degrees: 0, 90, 180, 270 console.log(result.isMirrored); // boolean console.log(result.isInverted); // boolean console.log(result.hasECI); // boolean console.log(result.bytes); // Uint8Array — raw encoded bytes console.log(result.position); // { topLeft, topRight, bottomLeft, bottomRight } console.log(result.symbologyIdentifier); // e.g. "]Q1" } ``` -------------------------------- ### readBarcodes Source: https://context7.com/sec-ant/zxing-wasm/llms.txt Decodes barcodes from various image input types. It accepts a Blob, File, ArrayBuffer, Uint8Array, or ImageData object and returns a Promise resolving to an array of detected barcode results. ```APIDOC ## readBarcodes(input, readerOptions?) ### Description Decodes barcodes from an image. Accepts a `Blob`, `File`, `ArrayBuffer`, `Uint8Array`, or duck-typed `ImageData` object as the image source and an optional `ReaderOptions` configuration. Returns a `Promise` where each element describes one detected barcode including its decoded text, format, symbology, position, orientation, and raw bytes. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { readBarcodes, type ReaderOptions } from "zxing-wasm/reader"; // --- from a URL (Blob) --- const imageBlob = await fetch( "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=Hello%20world!" ).then((r) => r.blob()); const options: ReaderOptions = { formats: ["QRCode"], tryHarder: true, tryRotate: true, tryInvert: true, tryDownscale: true, maxNumberOfSymbols: 5, binarizer: "LocalAverage", textMode: "HRI", eanAddOnSymbol: "Ignore", characterSet: "Unknown", returnErrors: false, isPure: false, }; const results = await readBarcodes(imageBlob, options); for (const result of results) { if (!result.isValid) { console.error("Failed:", result.error); continue; } console.log(result.text); console.log(result.format); console.log(result.symbology); console.log(result.contentType); console.log(result.orientation); console.log(result.isMirrored); console.log(result.isInverted); console.log(result.hasECI); console.log(result.bytes); console.log(result.position); console.log(result.symbologyIdentifier); } // --- from ImageData (e.g. canvas) --- const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d")!; const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const imgResults = await readBarcodes(imageData, { formats: ["EAN13", "UPCA"] }); // --- from ArrayBuffer --- const buffer = await imageBlob.arrayBuffer(); const bufResults = await readBarcodes(buffer); // --- in Node.js (no DOM ImageData needed — duck-typed) --- import { readFile } from "node:fs/promises"; const pngBuffer = await readFile("barcode.png"); const nodeResults = await readBarcodes(pngBuffer); // Uint8Array accepted directly ``` ### Response #### Success Response (200) - **results** (ReadResult[]) - An array of objects, each describing a detected barcode. - **text** (string) - The decoded text of the barcode. - **format** (string) - The format of the barcode (e.g., "QRCode", "EAN13"). - **symbology** (string) - The symbology of the barcode. - **contentType** (string) - The content type of the decoded data. - **orientation** (number) - The rotation of the barcode in degrees (0, 90, 180, 270). - **isMirrored** (boolean) - Indicates if the barcode was mirrored. - **isInverted** (boolean) - Indicates if the barcode was inverted. - **hasECI** (boolean) - Indicates if the barcode has an ECI (Extended Channel Interpretation) indicator. - **bytes** (Uint8Array) - The raw encoded bytes of the barcode. - **position** (object) - The coordinates of the barcode's corners: `{ topLeft, topRight, bottomLeft, bottomRight }`. - **symbologyIdentifier** (string) - An identifier for the barcode symbology (e.g., "]Q1"). - **isValid** (boolean) - Indicates if the barcode was successfully decoded and validated. - **error** (string) - An error message if `isValid` is false. #### Response Example ```json [ { "text": "Hello world!", "format": "QRCode", "symbology": "QRCode", "contentType": "Text", "orientation": 0, "isMirrored": false, "isInverted": false, "hasECI": false, "bytes": [ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33 ], "position": { "topLeft": {"x": 10, "y": 10}, "topRight": {"x": 190, "y": 10}, "bottomLeft": {"x": 10, "y": 190}, "bottomRight": {"x": 190, "y": 190} }, "symbologyIdentifier": "]Q1", "isValid": true, "error": null } ] ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.