### Install libheif-js Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/configuration.md Install the library using npm. All variants are available in the node_modules directory after installation. ```bash npm install libheif-js ``` -------------------------------- ### Node.js Usage Example Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/configuration.md Basic example demonstrating how to read a HEIC file and decode it using libheif-js in a Node.js environment. No additional configuration is needed for Node.js. ```javascript const libheif = require('libheif-js'); const fs = require('fs'); // No additional configuration needed const heicBuffer = fs.readFileSync('./photo.heic'); const decoder = new libheif.HeifDecoder(); const images = decoder.decode(heicBuffer); ``` -------------------------------- ### Manual Creation of DisplayImageData Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Example demonstrating how to manually create a DisplayImageData object with pre-allocated pixel data. ```javascript const width = 1440; const height = 960; const displayData = { data: new Uint8ClampedArray(width * height * 4), width: width, height: height }; ``` -------------------------------- ### HeifImage Display Callback Example Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md An example of how to use the DisplayCallback with HeifImage.display(). It checks for rendering success and uses putImageData to display the rendered pixels. ```javascript image.display(imageData, (displayData) => { if (!displayData) { console.error('Display failed'); return; } // displayData.data now contains the image pixels context.putImageData(displayData, 0, 0); }); ``` -------------------------------- ### Initialize HeifDecoder and Load HEIC Buffer Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/HeifDecoder.md Demonstrates initializing the HeifDecoder and reading a HEIC file into a buffer using Node.js 'fs' module. This setup is required before calling the decode method. ```javascript const libheif = require('libheif-js'); const fs = require('fs'); const decoder = new libheif.HeifDecoder(); const heicBuffer = fs.readFileSync('./photo.heic'); ``` -------------------------------- ### Decoding with Node.js Buffer Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Example of decoding a HEIF/HEIC file using a Node.js Buffer obtained from fs.readFileSync. ```javascript const buffer: Buffer = fs.readFileSync('./image.heic'); decoder.decode(buffer); ``` -------------------------------- ### Handle Display Callback Errors Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/quick-start.md This example shows how to properly handle errors that may occur during the image display process by checking the result of the display callback. ```javascript image.display(imageData, (displayData) => { if (!displayData) { console.error('Display failed'); return; // Don't continue if display failed } // Safe to use displayData here }); ``` -------------------------------- ### Initialize libheif-js Factory (Default/Bundled) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Call the factory function to get the libheif module instance for the default pure JavaScript or pre-bundled WebAssembly variants. ```javascript function libheifFactory(): LibheifModule ``` -------------------------------- ### WASM Dynamic Variant Factory - Custom Binary Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Use this example when you need to provide a custom WASM binary to the WASM dynamic factory. Ensure the binary path is correct. ```javascript const fs = require('fs'); const libheifModule = require('libheif-js/wasm'); const customWasm = fs.readFileSync('./my-libheif.wasm'); const libheif = libheifModule({ wasmBinary: customWasm }); const decoder = new libheif.HeifDecoder(); ``` -------------------------------- ### Get libheif Version Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Retrieve the version string of the included libheif library. This can be useful for debugging or compatibility checks. ```javascript const libheif = require('libheif-js'); const version = libheif.heif_get_version(); console.log(`libheif version: ${version}`); ``` -------------------------------- ### Handle Factory Errors (WASM Variant) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Provides an example of how to handle potential errors during the WASM module loading process, such as when the binary is not available. Includes a fallback mechanism to the default variant. ```javascript // WASM variant may fail if binary is not available try { const libheif = require('libheif-js/wasm'); } catch (error) { console.error('Failed to load WASM variant:', error.message); // Fallback to default variant const libheif = require('libheif-js'); } ``` -------------------------------- ### Get HEIF Version Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/INDEX.md Retrieve the version string of the libheif library using the heif_get_version function. ```javascript heif_get_version() ``` -------------------------------- ### Get libheif Version Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/configuration.md Use this snippet to retrieve the version of the libheif library that the npm package is built against. The version is returned as a string. ```javascript const libheif = require('libheif-js'); console.log(libheif.heif_get_version()); // "1.19.8" ``` -------------------------------- ### Webpack: Import Bundled Variant (Recommended) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/usage-patterns.md Use the pre-bundled WASM variant of libheif-js for simplicity. No special Webpack configuration is required beyond a standard setup. ```javascript // webpack.config.js (no special config needed) module.exports = { // Standard webpack config }; // src/index.js const libheif = require('libheif-js/wasm-bundle'); export function decodeHeic(buffer) { const decoder = new libheif.HeifDecoder(); return decoder.decode(buffer); } ``` -------------------------------- ### Handle WASM Binary Not Available Error Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/errors.md Provides solutions for the 'WASM Binary Not Available' error, including installing dependencies in Node.js or using the pre-bundled variant in the browser. ```javascript // In Node.js, ensure npm dependency is installed: // npm install libheif-js // In browser, either: // 1. Use wasm-bundle variant (pre-bundled) const libheif = require('libheif-js/wasm-bundle'); // 2. Configure bundler to handle .wasm files // See configuration.md for bundler setup ``` -------------------------------- ### Decoding with Uint8Array Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Example of decoding a HEIF/HEIC buffer using a Uint8Array, typically obtained from file reading operations in browsers or Node.js. ```javascript const buffer: Uint8Array = new Uint8Array(fileData); decoder.decode(buffer); ``` -------------------------------- ### Decode HEIC Image in Node.js Source: https://github.com/catdad-experiments/libheif-js/blob/master/README.md Read a HEIC file and decode it using libheif-js. This example assumes you are in a Node.js environment and have the 'fs' module available. ```javascript const file = fs.readFileSync('./temp/0002.heic'); const decoder = new libheif.HeifDecoder(); const data = decoder.decode(file); // data in an array holding all images inside the heic file const image = data[0]; const width = image.get_width(); const height = image.get_height(); ``` -------------------------------- ### ModuleFactory Properties and Usage Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md This snippet details the properties available on the initialized LibheifModule object returned by the ModuleFactory, including HeifDecoder and heif_get_version, along with an example of their usage. ```APIDOC ## LibheifModule Interface All factory functions return an object with this structure: ```typescript interface LibheifModule { HeifDecoder: class; heif_get_version(): string; // ... additional libheif C API bindings } ``` ### Properties | Name | Type | Description | |------|------|-------------| | HeifDecoder | constructor | Constructor for HEIF decoder instances | | heif_get_version | function | Returns the libheif version string | ### Example - Using Module Properties ```javascript const libheif = require('libheif-js'); // Access version console.log(libheif.heif_get_version()); // "1.19.8" // Create decoder const decoder = new libheif.HeifDecoder(); // Decode image const images = decoder.decode(heicBuffer); ``` ``` -------------------------------- ### Import Module Variants Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Import the libheif-js library using different module variants. Choose the appropriate import based on your project setup (e.g., standard JS, WASM, or bundled WASM). ```javascript const libheif = require('libheif-js'); ``` ```javascript const libheif = require('libheif-js/wasm'); ``` ```javascript const libheif = require('libheif-js/wasm-bundle'); ``` -------------------------------- ### Browser: Render HEIC Image to Canvas Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/usage-patterns.md Render a decoded HEIC image directly to an HTML5 canvas in the browser. This example shows how to handle file input and display the image. ```javascript async function displayHeicInCanvas(heicArrayBuffer, canvasElement) { const libheif = await import('https://cdn.jsdelivr.net/npm/libheif-js@1.19.8/libheif-wasm/libheif-bundle.mjs'); const decoder = new libheif.HeifDecoder(); // Decode from ArrayBuffer const heicData = new Uint8Array(heicArrayBuffer); const images = decoder.decode(heicData); if (!images || images.length === 0) { throw new Error('No images in file'); } const image = images[0]; const width = image.get_width(); const height = image.get_height(); // Setup canvas canvasElement.width = width; canvasElement.height = height; const context = canvasElement.getContext('2d'); const imageData = context.createImageData(width, height); // Render image return new Promise((resolve, reject) => { image.display(imageData, (displayData) => { if (!displayData) { reject(new Error('Display failed')); return; } context.putImageData(displayData, 0, 0); resolve(); }); }); } // Usage const fileInput = document.getElementById('heic-file'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; const arrayBuffer = await file.arrayBuffer(); const canvas = document.getElementById('preview'); await displayHeicInCanvas(arrayBuffer, canvas); }); ``` -------------------------------- ### Reuse Module Instances Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Illustrates the best practice of loading the module once and reusing the instance across multiple function calls to avoid repeated initialization overhead. ```javascript // GOOD: Load module once const libheif = require('libheif-js'); function processImage(buffer) { const decoder = new libheif.HeifDecoder(); return decoder.decode(buffer); } processImage(buffer1); processImage(buffer2); // Reuses loaded module ``` -------------------------------- ### Initialization Lifecycle Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Explains the synchronous initialization process for both the default and dynamic WASM variants of the ModuleFactory, including timelines. ```APIDOC ## Initialization Lifecycle ### Default and Bundled Variants 1. Module is required/imported 2. Factory function is called immediately (no arguments) 3. Returns initialized `LibheifModule` object 4. Ready for use **Timeline:** Synchronous, completes in microseconds ### Dynamic WASM Variant 1. Module is required 2. Factory function is called (may or may not pass options) 3. Factory loads WASM binary (from filesystem or provided options) 4. Initializes WASM memory and runtime 5. Returns initialized `LibheifModule` object **Timeline:** Synchronous (file I/O for WASM), completes in milliseconds ``` -------------------------------- ### Handle Module Not Found Error Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/errors.md Demonstrates how to catch and log a 'module not found' error when requiring a non-existent entry point in Node.js. ```javascript // This will throw because 'libheif-js/invalid' doesn't exist try { const libheif = require('libheif-js/invalid'); } catch (error) { console.error('Module not found:', error.message); } ``` -------------------------------- ### Get libheif-js Version Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Retrieve the current version of the libheif-js library. This is useful for compatibility checks and debugging. ```javascript const version = libheif.heif_get_version(); console.log(version); // "1.19.8" ``` -------------------------------- ### HeifImage Interface Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Represents a decoded HEIF/HEIC image. Provides methods to get dimensions and display the image. ```APIDOC ## HeifImage Interface ### Description Represents a decoded HEIF/HEIC image returned from `HeifDecoder.decode()`. ### Methods - **get_width()**: Returns image width in pixels. - **get_height()**: Returns image height in pixels. - **display(imageData: DisplayImageData, callback: DisplayCallback)**: Renders image data to an ImageData object. ``` -------------------------------- ### Run Tests with npm Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/MANIFEST.md Execute the package's test suite using npm. This command verifies the functionality of all module variants, decoding accuracy, and image processing capabilities. ```bash npm test ``` -------------------------------- ### Best Practices Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Provides guidance on best practices for using the ModuleFactory, including reusing module instances and handling potential factory errors, especially for the WASM variant. ```APIDOC ## Best Practices ### Reuse Module Instances ```javascript // GOOD: Load module once const libheif = require('libheif-js'); function processImage(buffer) { const decoder = new libheif.HeifDecoder(); return decoder.decode(buffer); } processImage(buffer1); processImage(buffer2); // Reuses loaded module ``` ### Avoid Repeated Factory Calls (WASM Variant) ```javascript // INEFFICIENT: Factory loads WASM binary each time const libheifFactory = require('libheif-js/wasm'); const lib1 = libheifFactory(); // Loads WASM const lib2 = libheifFactory(); // Loads WASM again // EFFICIENT: Call factory once const libheif = require('libheif-js/wasm'); // libheif is already initialized, no need for manual factory call ``` ### Handle Factory Errors ```javascript // WASM variant may fail if binary is not available try { const libheif = require('libheif-js/wasm'); } catch (error) { console.error('Failed to load WASM variant:', error.message); // Fallback to default variant const libheif = require('libheif-js'); } ``` ``` -------------------------------- ### Get HEIC Image Dimensions Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/quick-start.md Retrieve the width and height of the decoded HEIC image. This information is useful for rendering or further processing. ```javascript const image = images[0]; const width = image.get_width(); const height = image.get_height(); console.log(`${width}x${height}px`); ``` -------------------------------- ### Initialize WASM with Custom Binary Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/configuration.md Provide a pre-loaded WASM binary when initializing the WASM variant of libheif-js in Node.js. This is useful for custom WASM builds or loading from non-standard locations. ```javascript const fs = require('fs'); const wasmBinary = fs.readFileSync('./path/to/custom/libheif.wasm'); const libheifModule = require('libheif-js/wasm'); const libheif = libheifModule({ wasmBinary }); ``` -------------------------------- ### Esbuild Configuration for WASM Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/configuration.md Configure esbuild to bundle the application and handle .wasm files by setting the loader to 'binary'. ```javascript // build.js const esbuild = require('esbuild'); esbuild.build({ entryPoints: ['src/index.js'], bundle: true, outfile: 'bundle.js', loader: { '.wasm': 'binary', }, }); ``` -------------------------------- ### Get libheif-js Version Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/MANIFEST.md Retrieve the current version of the libheif-js library at runtime. This function returns a string representing the version number. ```javascript libheif.heif_get_version() ``` -------------------------------- ### Get Image Dimensions Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/00-START-HERE.txt Retrieve the width and height of a decoded HEIF image object. This is useful for pre-allocating buffers or for display purposes. ```javascript const width = image.get_width(); const height = image.get_height(); ``` -------------------------------- ### HeifDecoder Instantiation Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Demonstrates how to instantiate the HeifDecoder class, which is the primary entry point for decoding HEIC images. ```APIDOC ## Creating Instances ### HeifDecoder `HeifDecoder` is the only class meant for direct instantiation. Use it to decode HEIC image data. ```javascript // All three module variants provide these: const libheif = require('libheif-js'); // Instantiate the decoder const decoder = new libheif.HeifDecoder(); // The decode method returns an array of HeifImage instances // const images = decoder.decode(buffer); // const image = images[0]; // HeifImage instance ``` **Note:** Do not attempt to instantiate `HeifImage` directly. It is only created via `HeifDecoder.decode()`. ``` -------------------------------- ### HeifImage Interface Definition Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Defines the structure of a decoded HEIF/HEIC image object. It includes methods to get dimensions and display the image. ```typescript interface HeifImage { get_width(): number; get_height(): number; display(imageData: DisplayImageData, callback: DisplayCallback): void; } ``` -------------------------------- ### Load libheif-js (Script Tag - WASM Bundle) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Include the pre-bundled WASM version of libheif-js in an HTML file using a script tag. The library will be available globally. ```html ``` -------------------------------- ### Webpack: Import WASM Variant Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/usage-patterns.md Configure Webpack to handle the WASM variant of libheif-js. This setup is necessary when using the non-bundled WASM module. ```javascript // webpack.config.js module.exports = { module: { rules: [ { test: /\.wasm$/, type: 'webassembly/async', }, ], }, experiments: { asyncWebAssembly: true, }, }; // src/index.js const libheif = require('libheif-js/wasm'); export async function decodeHeic(buffer) { const decoder = new libheif.HeifDecoder(); const images = decoder.decode(buffer); return images; } ``` -------------------------------- ### Initialize libheif-js Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Import the libheif-js module. This object provides access to the HEIF decoder and utility functions. ```javascript const libheif = require('libheif-js'); ``` -------------------------------- ### Load libheif-js (CommonJS - WASM Bundle) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Import the pre-bundled WASM version of libheif-js using CommonJS syntax, which includes the WASM binary directly. ```javascript const libheif = require('libheif-js/wasm-bundle'); ``` -------------------------------- ### Access Module Properties Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Demonstrates how to access the `heif_get_version` function and instantiate `HeifDecoder` from the returned module. ```javascript const libheif = require('libheif-js'); // Access version console.log(libheif.heif_get_version()); // "1.19.8" // Create decoder const decoder = new libheif.HeifDecoder(); // Decode image const images = decoder.decode(heicBuffer); ``` -------------------------------- ### LibheifModule Interface Definition Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Defines the structure of the root module export from 'libheif-js'. It includes the HeifDecoder class and a utility function to get the library version. ```typescript interface LibheifModule { HeifDecoder: typeof HeifDecoder; heif_get_version(): string; } ``` -------------------------------- ### Get Decoded Image Height Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/HeifImage.md Retrieves the height of the decoded HEIF image in pixels. This is essential for correctly rendering the image or allocating appropriate memory buffers. ```javascript const libheif = require('libheif-js'); const decoder = new libheif.HeifDecoder(); const images = decoder.decode(heicBuffer); const image = images[0]; const height = image.get_height(); console.log(`Image height: ${height}px`); ``` -------------------------------- ### Initialize libheif-js Factory (Dynamic WASM) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Call the factory function with optional WASM binary options to initialize the dynamic WebAssembly variant of the libheif module. ```javascript function libheifFactory(options?: {wasmBinary?: ArrayBuffer | Buffer}): LibheifModule ``` -------------------------------- ### Import libheif-js (Node.js WASM Bundle) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Import the bundled WebAssembly (WASM) version of the libheif-js library in a Node.js environment. This includes the WASM runtime and is useful for simpler deployment. ```javascript const libheif = require('libheif-js/wasm-bundle'); const decoder = new libheif.HeifDecoder(); ``` -------------------------------- ### Check libheif Version and Compatibility Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/usage-patterns.md Retrieves the libheif version and logs a warning if the version is older than 1.17, which might affect feature availability. ```javascript function checkVersion() { const libheif = require('libheif-js'); const version = libheif.heif_get_version(); console.log(`libheif version: ${version}`); const [major, minor] = version.split('.').map(Number); if (major < 1 || (major === 1 && minor < 17)) { console.warn('Warning: Old libheif version, some features may not work'); } } checkVersion(); ``` -------------------------------- ### Get Decoded Image Width Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/HeifImage.md Retrieves the width of the decoded HEIF image in pixels. This is useful for setting up display surfaces or performing calculations based on image dimensions. ```javascript const libheif = require('libheif-js'); const decoder = new libheif.HeifDecoder(); const images = decoder.decode(heicBuffer); const image = images[0]; const width = image.get_width(); console.log(`Image width: ${width}px`); ``` -------------------------------- ### Check Node.js Version Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/quick-start.md Verify your Node.js version meets the minimum requirement of v8.0.0. ```bash node --version # Should be v8.0.0 or higher ``` -------------------------------- ### Load libheif-js (Script Tag - Pure JS) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Include the pure JavaScript version of libheif-js in an HTML file using a script tag. The library will be available globally. ```html ``` -------------------------------- ### Import libheif-js in Browser (ES Modules) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Import the libheif-js library in a browser environment using ES Modules. This approach uses a factory function to initialize the library, typically the WASM bundled version. ```javascript import libheifFactory from 'https://cdn.jsdelivr.net/npm/libheif-js@1.19.8/libheif-wasm/libheif-bundle.mjs'; const libheif = libheifFactory(); const decoder = new libheif.HeifDecoder(); ``` -------------------------------- ### Load libheif-js (CommonJS - WASM) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Import the WASM version of libheif-js using CommonJS syntax, which dynamically loads the WebAssembly binary. ```javascript const libheif = require('libheif-js/wasm'); ``` -------------------------------- ### Import libheif-js in CommonJS Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/MANIFEST.md Demonstrates how to import the libheif-js library in a CommonJS environment (Node.js or bundlers), showing three distribution variants. ```javascript // Pure JavaScript (default) const libheif = require('libheif-js'); ``` ```javascript // WebAssembly with dynamic loading const libheif = require('libheif-js/wasm'); ``` ```javascript // Pre-bundled WebAssembly const libheif = require('libheif-js/wasm-bundle'); ``` -------------------------------- ### CommonJS WASM Bundled Variant Factory Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md This snippet shows how to require the CommonJS bundled WASM variant of libheif-js. It's used when you need to import the library in a Node.js environment or a CommonJS-compatible setup. ```javascript module.exports = require('./libheif-wasm/libheif-bundle.js')(); ``` ```javascript const libheif = require('libheif-js/wasm-bundle'); const decoder = new libheif.HeifDecoder(); ``` -------------------------------- ### Pre-allocate Buffer for DisplayObject Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/DisplayObject.md Always pre-allocate the buffer before passing it to the display() method to ensure correct operation. This is the recommended approach for single image display. ```javascript // CORRECT: Pre-allocated buffer const displayData = { data: new Uint8ClampedArray(width * height * 4), width, height }; image.display(displayData, callback); // ✅ Works ``` -------------------------------- ### Prevent Invalid ImageData Buffer Errors in libheif-js Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/errors.md Ensure the `ImageData` object passed to `display()` has a buffer with the correct size (width * height * 4) to avoid memory corruption or undefined behavior. This example shows both correct and incorrect buffer allocations. ```javascript const width = image.get_width(); const height = image.get_height(); // CORRECT: buffer size is width * height * 4 const correctBuffer = new Uint8ClampedArray(width * height * 4); image.display({ data: correctBuffer, width, height }, callback); // INCORRECT: wrong buffer size const wrongBuffer = new Uint8ClampedArray(width * height); // Missing *4 image.display({ data: wrongBuffer, width, height }, callback); // Undefined behavior ``` -------------------------------- ### Node.js: Create DisplayObject as Plain Object Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/DisplayObject.md Use a plain JavaScript object with 'data', 'width', and 'height' properties for Node.js environments. Ensure 'data' is a Uint8ClampedArray of the correct size. ```javascript const width = 1440; const height = 960; const displayData = { data: new Uint8ClampedArray(width * height * 4), width: width, height: height }; image.display(displayData, callback); ``` -------------------------------- ### WASM Dynamic Variant Factory - Auto-load Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md This factory is for the WASM dynamic variant. It automatically loads the WASM binary from the filesystem if not provided. ```javascript const fs = require('fs'); const wasmBinary = fs.readFileSync('./libheif-wasm/libheif.wasm'); module.exports = require('./libheif-wasm/libheif.js')({ wasmBinary }); ``` ```javascript const libheif = require('libheif-js/wasm'); const decoder = new libheif.HeifDecoder(); ``` -------------------------------- ### Instantiate HeifDecoder Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Create a new instance of the HeifDecoder class to begin decoding HEIF images. ```javascript new HeifDecoder() ``` -------------------------------- ### Decoding with Array-like Buffer Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Demonstrates decoding using a generic array-like object, which must have a 'length' property and indexed elements. ```javascript const buffer: ArrayLike = { length: 100, [0]: 255, [1]: 254, // ... more indices }; decoder.decode(buffer); ``` -------------------------------- ### Import libheif-js (Node.js WASM) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Import the WebAssembly (WASM) variant of the libheif-js library in a Node.js environment. This version typically offers better performance for decoding. ```javascript const libheif = require('libheif-js/wasm'); const decoder = new libheif.HeifDecoder(); ``` -------------------------------- ### HeifDecoder Constructor Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Initializes a new instance of the HeifDecoder class. ```APIDOC ## HeifDecoder() ### Description Creates a new HeifDecoder instance. ### Signature `constructor()` ### Returns `HeifDecoder` - A new HeifDecoder object. ``` -------------------------------- ### HeifDecoder Constructor Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Instantiate the HEIF/HEIC decoder. This constructor is available directly from the root module export. ```APIDOC ## HeifDecoder Constructor ### Description Constructor function for the HEIF/HEIC decoder class. Returns a new `HeifDecoder` instance when called with `new`. ### Method `new HeifDecoder()` ### Example ```javascript const libheif = require('libheif-js'); const decoder = new libheif.HeifDecoder(); ``` ``` -------------------------------- ### Webpack Configuration for WASM Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/configuration.md Configure webpack to handle .wasm files for the WASM variant. Ensure asyncWebAssembly is enabled in experiments. ```javascript // webpack.config.js module.exports = { module: { rules: [ { test: /\.wasm$/, type: 'webassembly/async', }, ], }, experiments: { asyncWebAssembly: true, }, }; ``` -------------------------------- ### Include libheif-js via Browser Script Tag Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/MANIFEST.md Illustrates how to include the libheif-js library in an HTML file using script tags, offering both pure JavaScript and bundled WebAssembly options. ```html ``` ```html ``` -------------------------------- ### Instantiate HeifDecoder Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Create a new instance of the HeifDecoder. This is the primary class for decoding HEIF/HEIC images. ```javascript const libheif = require('libheif-js'); const decoder = new libheif.HeifDecoder(); const images = decoder.decode(heicBuffer); ``` -------------------------------- ### Load libheif-js (ES Modules - Browser) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/RootModule.md Import the pre-bundled WASM version of libheif-js as an ES Module, intended for use in modern browsers. ```javascript import libheif from 'https://cdn.jsdelivr.net/npm/libheif-js@1.19.8/libheif-wasm/libheif-bundle.mjs'; const decoder = new libheif().HeifDecoder(); ``` -------------------------------- ### DisplayImageData using Browser Canvas Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/types.md Shows how to obtain a DisplayImageData-compatible object using the browser's CanvasRenderingContext2D.createImageData() method. ```javascript const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const context = canvas.getContext('2d'); const imageData = context.createImageData(width, height); // imageData satisfies DisplayImageData ``` -------------------------------- ### ModuleFactory Default and Bundled Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Factory function signature for the default and bundled WASM variants of libheif-js. ```APIDOC ## ModuleFactory Default and Bundled ### Description Factory function for the default and bundled module variants. ### Signature ```javascript function libheifFactory(): LibheifModule ``` ``` -------------------------------- ### Include Pure JS libheif-js via Script Tag Source: https://github.com/catdad-experiments/libheif-js/blob/master/README.md Include the pure-JavaScript implementation in an HTML page using a script tag. This exposes a 'libheif' global. ```html ``` -------------------------------- ### Avoid Repeated Factory Calls (WASM Variant) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/ModuleFactory.md Highlights an inefficient pattern of repeatedly calling the WASM factory function, which leads to multiple WASM binary loads. Shows the efficient approach of calling the factory only once. ```javascript // INEFFICIENT: Factory loads WASM binary each time const libheifFactory = require('libheif-js/wasm'); const lib1 = libheifFactory(); // Loads WASM const lib2 = libheifFactory(); // Loads WASM again // EFFICIENT: Call factory once const libheif = require('libheif-js/wasm'); // libheif is already initialized, no need for manual factory call ``` -------------------------------- ### Render Image Data to Buffer (Node.js PNG Export) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/HeifImage.md Renders the decoded HEIF image data to a buffer suitable for saving as a PNG file in a Node.js environment. This involves creating a display object with pre-allocated data and then using the 'pngjs' library to write the buffer to a PNG file. Errors are reported via the callback. ```javascript const libheif = require('libheif-js'); const { PNG } = require('pngjs'); const fs = require('fs'); const decoder = new libheif.HeifDecoder(); const heicBuffer = fs.readFileSync('./photo.heic'); const images = decoder.decode(heicBuffer); const image = images[0]; const width = image.get_width(); const height = image.get_height(); image.display( { data: new Uint8ClampedArray(width * height * 4), width, height }, (displayData) => { if (!displayData) { console.error('HEIF processing error'); return; } const png = new PNG({ width, height }); png.data = Buffer.from(displayData.data); const buffer = PNG.sync.write(png); fs.writeFileSync('./output.png', buffer); } ); ``` -------------------------------- ### HeifImage.display Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/INDEX.md Renders the HEIF image to a provided buffer using a callback. ```APIDOC ## HeifImage.display() ### Description Renders the image to a buffer and calls a callback function upon completion. ### Signature `display(imageData, callback)` ### Parameters #### Path Parameters - **imageData** (DisplayImageData) - Required - The buffer to render the image into. - **callback** (DisplayCallback) - Required - The function to call after rendering. ### Returns `void` ``` -------------------------------- ### Render Image to Pixels Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/00-START-HERE.txt Renders a decoded HEIF image into a RGBA pixel buffer. The callback function receives the display data, which can then be used for rendering. ```javascript image.display( { data: new Uint8ClampedArray(width*height*4), width, height }, (displayData) => { if (displayData) { // displayData.data contains RGBA pixels } } ); ``` -------------------------------- ### Handle Display Callback Failure in libheif-js Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/errors.md Use this pattern when the `display()` callback might receive `null`, indicating a rendering failure after successful decoding. Check the `displayData` parameter to gracefully handle such errors. ```javascript const libheif = require('libheif-js'); const fs = require('fs'); const heicBuffer = fs.readFileSync('./photo.heic'); const decoder = new libheif.HeifDecoder(); const images = decoder.decode(heicBuffer); const image = images[0]; const width = image.get_width(); const height = image.get_height(); image.display( { data: new Uint8ClampedArray(width * height * 4), width, height }, (displayData) => { if (!displayData) { console.error('HEIF processing error: display failed'); // Retry, skip image, or degrade gracefully return; } // displayData is valid, process it console.log('Display successful'); } ); ``` -------------------------------- ### Node.js: Convert HEIC to PNG Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/usage-patterns.md Use this pattern in Node.js to convert a HEIC file to PNG format. It requires the 'libheif-js', 'pngjs', and 'fs' libraries. Ensure the input HEIC file exists and the output path is writable. ```javascript const libheif = require('libheif-js'); const { PNG } = require('pngjs'); const fs = require('fs'); async function heicToPng(inputPath, outputPath) { // Read HEIC file const heicBuffer = fs.readFileSync(inputPath); // Decode HEIC const decoder = new libheif.HeifDecoder(); const images = decoder.decode(heicBuffer); if (!images || images.length === 0) { throw new Error('No images found in HEIC file'); } const image = images[0]; const width = image.get_width(); const height = image.get_height(); // Render to pixel data const pixelData = await new Promise((resolve, reject) => { image.display( { data: new Uint8ClampedArray(width * height * 4), width, height }, (displayData) => { if (!displayData) { reject(new Error('Display failed')); } else { resolve(displayData); } } ); }); // Create PNG const png = new PNG({ width, height }); png.data = Buffer.from(pixelData.data); // Write PNG png.pack().pipe(fs.createWriteStream(outputPath)); return new Promise((resolve, reject) => { png.on('end', resolve); png.on('error', reject); }); } // Usage heicToPng('./photo.heic', './photo.png') .then(() => console.log('Conversion complete')) .catch(err => console.error('Conversion failed:', err.message)); ``` -------------------------------- ### Asynchronous Display Method Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/MANIFEST.md The display() method is asynchronous and uses callbacks. Other methods like decode() and get_width() are synchronous. ```javascript const images = decoder.decode(buffer); const width = image.get_width(); image.display(imageData, (displayData) => { // Use displayData here }); ``` -------------------------------- ### Accessing Pixel Data in DisplayObject Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/DisplayObject.md Demonstrates how to create a DisplayObject and access individual pixel data using calculated indices. The `data` property is a `Uint8ClampedArray` storing RGBA values. ```javascript const displayData = { data: new Uint8ClampedArray(100 * 100 * 4), width: 100, height: 100 }; // Access pixel at (x=10, y=20) const pixelIndex = (20 * 100 + 10) * 4; const red = displayData.data[pixelIndex]; const green = displayData.data[pixelIndex + 1]; const blue = displayData.data[pixelIndex + 2]; const alpha = displayData.data[pixelIndex + 3]; ``` -------------------------------- ### Convert Display Data to PNG (Node.js) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/api-reference/DisplayObject.md Converts display data into a PNG object using the 'pngjs' library. This is suitable for server-side image generation. Requires 'pngjs' and 'fs' modules. ```javascript const { PNG } = require('pngjs'); function displayDataToPng(displayData) { const png = new PNG({ width: displayData.width, height: displayData.height }); // Copy pixel data png.data = Buffer.from(displayData.data); return png; } // Usage image.display(displayData, (result) => { if (result) { const png = displayDataToPng(result); png.pack().pipe(fs.createWriteStream('output.png')); } }); ``` -------------------------------- ### Utility Functions Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/_GENERATION_REPORT.md Provides utility functions for interacting with the libheif-js library. ```APIDOC ## Function: heif_get_version() ### Description Returns the version string of the libheif library. ### Returns - `string`: The version of the libheif library. ``` -------------------------------- ### Handle Callback Timing Errors (Correct) Source: https://github.com/catdad-experiments/libheif-js/blob/master/_autodocs/errors.md Demonstrates the correct way to handle asynchronous callbacks by accessing and processing the data exclusively within the callback function's scope. ```javascript image.display(displayData, (result) => { if (!result) { console.error('Display failed'); return; } // CORRECT: use result inside callback console.log(result.data); }); ```