### Install heic-to with npm Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/integration-guide.md Install the heic-to library using npm. This is the first step to using the library in your project. ```bash npm install heic-to ``` -------------------------------- ### Start local development server Source: https://github.com/hoppergee/heic-to/blob/main/README.md Run `yarn s` to start the local development server for testing changes. This will typically open `http://127.0.0.1:8080/example/`. ```bash yarn s ``` -------------------------------- ### Example Usage: Complete Implementation (Main Thread) Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md A complete example for the main thread that checks for Web Worker support, creates a worker, handles messages and errors, and sends a file for conversion. ```javascript // main.js const file = document.getElementById("fileInput").files[0] // Check if browser supports workers if (typeof Worker !== 'undefined') { const worker = new Worker("converter.js", { type: "module" }) worker.onmessage = (event) => { if (event.data.success) { const url = URL.createObjectURL(event.data.blob) document.getElementById("image").src = url } else { alert("Conversion failed: " + event.data.error) } } worker.onerror = (error) => { console.error("Worker error:", error) } worker.postMessage({ file }) } else { console.error("Web Workers not supported") } ``` -------------------------------- ### Total Conversion Time Example Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md An example calculation of total conversion time, combining worker initialization, decoding, and encoding durations. ```text First conversion: worker init (50ms) + decode (300ms) + encode (150ms) = 500ms Subsequent: decode (300ms) + encode (150ms) = 450ms ``` -------------------------------- ### Example Usage of IIFE Build in an HTML Page Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md This example demonstrates how to include the heic-to library via a CDN script tag and use the global `HeicTo` object to convert a HEIC file selected by the user into a JPEG blob. ```html ``` -------------------------------- ### Install build dependencies on Mac Source: https://github.com/hoppergee/heic-to/blob/main/README.md Before building libheif.js, install necessary dependencies using Homebrew. This includes cmake, make, pkg-config, x265, libde265, libjpeg, libtool, and emscripten. ```bash brew install cmake make pkg-config x265 libde265 libjpeg libtool brew install emscripten git clone git@github.com:strukturag/libheif.git ``` -------------------------------- ### ImageBitmap Creation with Options Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/types.md Example demonstrating how to use heicTo to convert a HEIC file to an ImageBitmap with specific options for orientation and resizing. ```javascript import { heicTo } from "heic-to" const file = document.getElementById("fileInput").files[0] const bitmap = await heicTo({ blob: file, type: "bitmap", options: { imageOrientation: "flipY", resizeWidth: 800, resizeHeight: 600, resizeQuality: "high" } }) // Draw to canvas at correct orientation const canvas = document.getElementById("canvas") const ctx = canvas.getContext("2d") ctx.drawImage(bitmap, 0, 0) ``` -------------------------------- ### Worker Initialization Timings Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Provides approximate timings for the initial worker setup process, including loading the worker script and creating the worker instance. ```javascript // Timings (approximate) loadWorker() // ~0-5ms new Blob() // <1ms new Worker() // ~10-50ms ``` -------------------------------- ### Checking heic-to installation with npm Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md This command-line instruction shows how to check if the heic-to package is installed in your project using npm, which can be part of a bundle analysis. ```bash npm list heic-to ``` -------------------------------- ### Worker Error Handling Setup Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/errors.md Shows the basic setup for a worker's onerror handler. Errors thrown within the worker will be logged to the console. For more advanced handling, a wrapper function is suggested. ```javascript worker = new Worker(URL.createObjectURL(workerBlob)) worker.onerror = (error) => console.error('Worker error:', error) ``` ```javascript import { heicTo } from "heic-to" // Add custom error handler (if library exposes it) // Otherwise, errors will appear in browser console as: // "Worker error: Error: [message]" // Implement a wrapper with better error handling let workerError = null const originalFetch = window.fetch try { const blob = await heicTo({ blob: file, type: "image/jpeg" }) } catch (error) { console.error("heic-to error:", error) } ``` -------------------------------- ### HEIC to ImageBitmap Conversion Example Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/types.md Illustrates converting a HEIC file to an ImageBitmap, specifying 'bitmap' as the output type. ```javascript const bitmap: ImageBitmap = await heicTo({ blob: file, type: "bitmap", options: { imageOrientation: "flipY" } }) ``` -------------------------------- ### Default Build Example Usage Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Demonstrates converting a HEIC file to JPEG in a browser using the default heic-to build. Ensure your CSP allows `unsafe-eval` and `blob:` workers. ```javascript import { heicTo, isHeic } from "heic-to" // Get file from input const file = document.getElementById("fileInput").files[0] // Check format if (await isHeic(file)) { // Convert to JPEG const jpeg = await heicTo({ blob: file, type: "image/jpeg", quality: 0.85 }) // Display result const url = URL.createObjectURL(jpeg) document.getElementById("image").src = url } ``` -------------------------------- ### Example Usage: Main Thread Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Demonstrates how to set up a Web Worker from the main thread to handle HEIC image conversion. It sends a file to the worker and displays the resulting blob. ```javascript import { heicTo, isHeic } from "heic-to/next" const file = document.getElementById("fileInput").files[0] // Create a worker const worker = new Worker("worker.js", { type: "module" }) // Send file to worker worker.postMessage({ file }) // Receive result worker.onmessage = (event) => { const { blob } = event.data const url = URL.createObjectURL(blob) document.getElementById("image").src = url } ``` -------------------------------- ### Using Multiple heic-to Builds in an Application Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md This example shows how to load the IIFE build via CDN for legacy browser support and then use it to convert a file. It also contrasts this with using ESM imports in a modern application. ```html ``` ```javascript // Modern app can also use ESM import { heicTo } from "heic-to" const blob = await heicTo({ blob: file, type: "image/jpeg" }) ``` -------------------------------- ### Example Usage: Complete Implementation (Worker Thread) Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md The worker script (`converter.js`) for the complete implementation. It imports the necessary functions and handles the HEIC to blob conversion, posting the result back. ```javascript // converter.js import { heicTo, isHeic } from "heic-to/next" self.onmessage = async (event) => { const { file } = event.data try { const blob = await heicTo({ blob: file, type: "image/jpeg", quality: 0.85 }) self.postMessage({ success: true, blob }) } catch (error) { self.postMessage({ success: false, error: error.toString() }) } } ``` -------------------------------- ### CSP-Safe Build Example Usage Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Demonstrates converting a HEIC file to JPEG in a browser using the CSP-safe heic-to build. This variant is compatible with strict CSP policies. ```javascript import { heicTo, isHeic } from "heic-to/csp" const file = document.getElementById("fileInput").files[0] if (await isHeic(file)) { const blob = await heicTo({ blob: file, type: "image/jpeg", quality: 0.8 }) const url = URL.createObjectURL(blob) document.getElementById("image").src = url } ``` -------------------------------- ### Unit Tests for isHeic() Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Provides unit test examples for verifying isHeic() behavior with PNG and HEIC files using ArrayBuffer and File objects. ```javascript // Test: PNG file returns false const pngBuffer = new ArrayBuffer([...]) const pngFile = new File([pngBuffer], "test.png", { type: "image/png" }) const result = await isHeic(pngFile) console.assert(result === false, "PNG should return false") // Test: HEIC file returns true const heicBuffer = new ArrayBuffer([ 0x00, 0x00, 0x00, 0x20, // Size 0x66, 0x74, 0x79, 0x70, // "ftyp" 0x68, 0x65, 0x69, 0x63, // "heic" ... ]) const heicFile = new File([heicBuffer], "test.heic", { type: "image/heic" }) const result = await isHeic(heicFile) console.assert(result === true, "HEIC should return true") ``` -------------------------------- ### HEIC to Image MIME Type Conversion Example Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/types.md Demonstrates converting a HEIC file to a specified image MIME type, such as JPEG, with quality options. ```javascript const blob: Blob = await heicTo({ blob: file, type: "image/jpeg", quality: 0.8 }) ``` -------------------------------- ### No Progress Reporting Example Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md A comment indicating the absence of a progress callback during the decoding process within the worker. ```javascript // No way to report: "50% decoded" to user ``` -------------------------------- ### Handle File Input for HEIC Conversion Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/types.md This example demonstrates how to handle file input changes, check if the file is a HEIC image using `isHeic`, and then convert it to JPEG. It logs file properties like name, size, and modification date. ```javascript import { heicTo, isHeic } from "heic-to" const fileInput = document.getElementById("fileInput") fileInput.addEventListener("change", async (event) => { const file = event.target.files[0] // This is a File object console.log("Filename:", file.name) console.log("Size:", file.size, "bytes") console.log("Last modified:", new Date(file.lastModified)) if (await isHeic(file)) { const converted = await heicTo({ blob: file, // File is accepted as a Blob type: "image/jpeg", quality: 0.8 }) } }) ``` -------------------------------- ### Basic HEIC File Detection in JavaScript Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Shows a basic example of how to use the isHeic() function with a file input element. It logs whether the selected file is in HEIC/HEIF format. ```javascript import { isHeic } from "heic-to" const fileInput = document.getElementById("fileInput") fileInput.addEventListener("change", async (event) => { const file = event.target.files[0] if (await isHeic(file)) { console.log("File is HEIC/HEIF format") } else { console.log("File is not HEIC/HEIF format") } }) ``` -------------------------------- ### Example Usage: Worker Thread Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Provides the code for the worker script (`worker.js`) that receives a file, checks if it's a HEIC, converts it, and posts the result back to the main thread. ```javascript // worker.js import { heicTo, isHeic } from "heic-to/next" self.onmessage = async (event) => { const { file } = event.data try { const isHeicFile = await isHeic(file) if (isHeicFile) { const blob = await heicTo({ blob: file, type: "image/jpeg", quality: 0.85 }) self.postMessage({ success: true, blob }) } else { self.postMessage({ success: false, reason: "Not a HEIC file" }) } } catch (error) { self.postMessage({ success: false, error: error.toString() }) } } ``` -------------------------------- ### Worker Communication Timeout Example Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/errors.md Demonstrates how to wrap the heicTo function with a custom timeout to prevent indefinite hanging. This is useful when dealing with potentially large files or unstable worker environments. ```javascript const decodeBuffer = async (buffer) => { return new Promise((resolve, reject) => { loadWorker() const id = (Math.random() * new Date().getTime()).toString(); const message = { id, buffer }; worker.postMessage(message); const handleEvent = (event) => { if (event.data.id === id) { event.currentTarget.removeEventListener("message", handleEvent); event.currentTarget.removeEventListener("error", handleError); if (event.data.error) { return reject(event.data.error); } return resolve(event.data.imageData); } } // ... no timeout configured ... }); } ``` ```javascript import { heicTo } from "heic-to" // Implement your own timeout wrapper async function heicToWithTimeout(args, timeoutMs = 30000) { return Promise.race([ heicTo(args), new Promise((_, reject) => setTimeout(() => reject(new Error('heic-to timeout')), timeoutMs) ) ]) } try { const blob = await heicToWithTimeout( { blob: file, type: "image/jpeg", quality: 0.8 }, 30000 // 30 second timeout ) } catch (error) { if (error.message === 'heic-to timeout') { console.error("Conversion took too long, likely file is too large or corrupt") } else { console.error("Conversion failed:", error) } } ``` -------------------------------- ### Catching Generic Worker Initialization Errors Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/errors.md This example shows how to catch potential errors when using heic-to, which might include web worker initialization failures. It logs the error message and checks for specific keywords to identify worker-related issues. ```javascript import { heicTo } from "heic-to" try { const blob = await heicTo({ blob: file, type: "image/jpeg" }) } catch (error) { // Worker initialization failures manifest as generic Error console.error("Worker error:", error.message || error) // Check error message for clues if (error.message && error.message.includes('Worker')) { console.error("Web Worker initialization failed") } } ``` -------------------------------- ### heic-to Module API Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/README.md The main module provides two core functions: `isHeic()` for detecting HEIC format and `heicTo()` for converting HEIC files to other image formats or ImageBitmaps. This section details their signatures, return types, error conditions, and usage examples. ```APIDOC ## heic-to Module API ### Description Provides core functionality for HEIC image processing. ### Functions #### `isHeic(file: File | Blob): Promise` ##### Description Detects if a given file or blob is in HEIC format by inspecting its binary header. ##### Parameters - **file** (File | Blob) - Required - The file or blob to check. ##### Returns - `Promise` - A promise that resolves to `true` if the file is HEIC, `false` otherwise. ##### Error Handling - Throws "HEIF image not found" if the file header is invalid or missing. ##### Usage Example ```javascript const isHeicImage = await isHeic(myFile); console.log(isHeicImage); ``` #### `heicTo({blob, type, quality, options}): Promise` ##### Description Converts a HEIC image file to a specified output format (e.g., JPEG, PNG) or an ImageBitmap. ##### Parameters - **blob** (File | Blob) - Required - The HEIC file to convert. - **type** (HeicTarget) - Required - The desired output format. Can be a MIME type string (e.g., "image/jpeg") or "bitmap". - **quality** (number) - Optional - The quality setting for lossy formats like JPEG (0.0 to 1.0). - **options** (ImageBitmapOptions) - Optional - Additional options for creating an ImageBitmap. ##### Returns - `Promise` - A promise that resolves to a Blob of the converted image or an ImageBitmap. ##### Error Handling - Throws "HEIF image not found" if the input is not a valid HEIC file. - Throws "HEIF processing error" if decoding or processing fails. - Throws "Can't convert canvas to blob." if encoding to a Blob fails. ##### Usage Example ```javascript // Convert to JPEG Blob const jpegBlob = await heicTo({ blob: heicFile, type: "image/jpeg", quality: 0.8 }); // Convert to ImageBitmap const bitmap = await heicTo({ blob: heicFile, type: "bitmap" }); ``` ``` -------------------------------- ### Get Image Height Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Retrieves the height of a decoded HEIF image in pixels. ```javascript const height = image.get_height() ``` -------------------------------- ### Get Image Width Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Retrieves the width of a decoded HEIF image in pixels. ```javascript const width = image.get_width() ``` -------------------------------- ### Allocate Resources in Worker Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Demonstrates how to allocate and initialize resources like the HEIF decoder and image buffers within a worker thread. ```javascript // Input const buffer = message.data.buffer // Large ArrayBuffer // Processing const decoder = new libheif.HeifDecoder() // WASM object const data = decoder.decode(buffer) // Array of images const image = data[0] // Single image const whiteImage = new ImageData(width, height) // Pixel container ``` -------------------------------- ### Libheif Initialization Variants Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Shows how to import the libheif builder function based on the build variant. All variants export a builder function. ```javascript // Default and IIFE builds import buildLibheif from "../../src/lib/libheif" // CSP-safe build import buildLibheif from "../../../src/lib/libheif-without-unsafe-eval" // All variants export a builder function const libheif = buildLibheif() ``` -------------------------------- ### ImageMime Type Definition Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/types.md A template literal type representing any valid image MIME type. It ensures the string starts with 'image/' but allows any format. ```typescript type ImageMime = `${ ``` -------------------------------- ### Build Configuration Difference (esbuild) Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Illustrates the esbuild configuration difference between the standard and CSP-safe builds of heic-to, highlighting how the worker file content is handled. ```javascript // Standard build const workerFileContent = fs.readFileSync('tmp/worker.js', 'utf8') define: { WORKER_FILE_CONTENT: JSON.stringify(workerFileContent) } // CSP-safe build const cspWorkerFileContent = fs.readFileSync('tmp/csp/worker.js', 'utf8') const worker_js = copyAndReplace( "src/worker.js", "tmp/src/csp/worker.js", /LIB_HEIF_PATH/, '"../../../src/lib/libheif-without-unsafe-eval"' ) define: { WORKER_FILE_CONTENT: JSON.stringify(cspWorkerFileContent) } ``` -------------------------------- ### Use CSP-Safe Variant of heic-to Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/errors.md Demonstrates how to import the CSP-safe variant of the `heicTo` function to avoid 'Refused to evaluate a string as JavaScript' errors in strict Content Security Policy environments. ```javascript // Instead of: import { heicTo } from "heic-to" // Use CSP-safe variant: import { heicTo } from "heic-to/csp" ``` -------------------------------- ### Parallel Conversion of Multiple Files Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Demonstrates how to convert multiple HEIC files in parallel using multiple Web Workers. This approach maximizes throughput for batch processing. ```javascript import { heicTo } from "heic-to/next" const files = [file1, file2, file3] // Create multiple workers for parallel processing const workers = Array(3) .fill(null) .map(() => new Worker("converter.js", { type: "module" })) // Send files to workers files.forEach((file, i) => { workers[i].postMessage({ file }) }) // Collect results const results = await Promise.all( workers.map(worker => new Promise(resolve => { worker.onmessage = (event) => resolve(event.data) })) ) ``` -------------------------------- ### Default Build Entry Point Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Imports the default build of heic-to, suitable for standard browser environments. Requires `unsafe-eval` for worker code. ```javascript import { heicTo, isHeic } from "heic-to" ``` -------------------------------- ### Get File MIME Type with HTML5 File API Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Shows how to retrieve the MIME type of a file selected via an HTML input element using the File API. ```javascript const file = document.getElementById("fileInput").files[0] console.log(file.type) // "image/jpeg" or "" (empty if unknown) ``` -------------------------------- ### Receive and Use ImageData in Main Thread Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Shows how to receive ImageData in the main thread and render it onto an HTML canvas. ```javascript // Receive ImageData from worker const imageData = event.data.imageData // Use in canvas ctx.putImageData(imageData, 0, 0) // Canvas can now be accessed/modified by main thread // GC will clean up the ImageData when canvas is released ``` -------------------------------- ### Handle Content Security Policy (CSP) issues Source: https://github.com/hoppergee/heic-to/blob/main/README.md If you encounter 'unsafe-eval' errors due to CSP, import `heicTo` from 'heic-to/csp' to resolve the issue. ```diff - import { heicTo } from "heic-to" + import { heicTo } from "heic-to/csp" ``` -------------------------------- ### Usage of heic-to IIFE Build Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/heic-to.md Use this snippet when integrating heic-to into a browser environment that does not have a module system. The library is exposed globally as `window.HeicTo`. Ensure the script is loaded before use. ```html ``` -------------------------------- ### Non-HEIC File Detection Examples Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Demonstrates how the isHeic() function returns false for common image and video formats that are not HEIC/HEIF. This includes JPEG, PNG, WebP, GIF, and standard MP4 files. ```javascript await isHeic(jpegFile) // false — JPEG await isHeic(pngFile) // false — PNG await isHeic(webpFile) // false — WebP await isHeic(gifFile) // false — GIF await isHeic(mp4File) // false — MP4 (different brand) ``` -------------------------------- ### CSP-Safe Build Entry Point Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Imports the CSP-safe build of heic-to, designed for environments with strict Content Security Policy. Does not require `unsafe-eval`. ```javascript import { heicTo, isHeic } from "heic-to/csp" ``` -------------------------------- ### Convert HEIC to ImageBitmap with Options Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/heic-to.md Converts a HEIC file to an ImageBitmap with specified options for orientation and resizing. The 'options' object allows for fine-tuning the conversion process. ```javascript import { heicTo } from "heic-to" const file = document.getElementById("fileInput").files[0] const imageBitmap = await heicTo({ blob: file, type: "bitmap", options: { imageOrientation: "flipY", resizeWidth: 800, resizeHeight: 600 } }) ``` -------------------------------- ### Initialize ImageData Alpha Channel Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Prepares an ImageData container for libheif rendering, initializing the alpha channel to fully opaque (255). ```javascript // Container prepared by worker const whiteImage = new ImageData(width, height) // Alpha channel initialized to 255 (fully opaque) for (let i = 0; i < width * height; i++) { whiteImage.data[i * 4 + 3] = 255; // Index 3, 7, 11, ... are alpha } // libheif fills in R, G, B values image.display(whiteImage, (displayData) => { // displayData.data = [r0,g0,b0,255, r1,g1,b1,255, ...] }) ``` -------------------------------- ### Conditional Image Conversion Based on HEIC Detection Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Provides an example of processing an image file: if it's HEIC, it's converted to JPEG; otherwise, the original file is returned. This demonstrates a practical use case for isHeic() in a file upload workflow. ```javascript import { heicTo, isHeic } from "heic-to" async function processImage(file) { const isHeicFile = await isHeic(file) if (isHeicFile) { // Convert HEIC to JPEG return await heicTo({ blob: file, type: "image/jpeg", quality: 0.85 }) } else { // Return original file return file } } const input = document.getElementById("fileInput") input.addEventListener("change", async (event) => { const file = event.target.files[0] const result = await processImage(file) // result is either converted Blob or original File }) ``` -------------------------------- ### Correct Usage of Async/Await with heic-to Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/README.md Shows the correct way to use the asynchronous functions provided by heic-to. Always use 'await' when calling functions like heicTo to ensure you receive the resolved value (e.g., a blob) instead of a Promise. ```javascript // Correct const result = await heicTo(args) // Wrong const result = heicTo(args) // Promise, not blob ``` -------------------------------- ### Worker Initialization Code Context Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/errors.md This code snippet shows the internal logic for loading a web worker, including creating a Blob from worker code, generating an object URL, and setting up an error handler. ```javascript const loadWorker = () => { if (!worker) { const workerFileContent = WORKER_FILE_CONTENT const workerBlob = new Blob([workerFileContent], {type: 'application/javascript'}) worker = new Worker(URL.createObjectURL(workerBlob)) worker.onerror = (error) => console.error('Worker error:', error) } return worker } ``` -------------------------------- ### Integration Test for isHeic() with Real File Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Demonstrates an integration test for isHeic() using a real HEIC file selected through an HTML file input. ```javascript // Test with real HEIC file const input = document.getElementById("fileInput") // Select a real HEIC file input.files[0] = heicFile const result = await isHeic(input.files[0]) console.assert(result === true, "Real HEIC file should be detected") ``` -------------------------------- ### CSP-Safe Build Implementation in HTML Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/integration-guide.md Set the Content Security Policy header and use the CSP-safe build of heic-to in your HTML. This ensures secure script execution. ```html ``` -------------------------------- ### Initialize libheif Decoder Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Creates a new HEIF decoder instance using the libheif API. ```javascript const decoder = new libheif.HeifDecoder() ``` -------------------------------- ### Build libheif.js with Emscripten Source: https://github.com/hoppergee/heic-to/blob/main/README.md Execute the build script for libheif.js. You can choose to build with or without `unsafe-eval` by setting the `USE_UNSAFE_EVAL` variable. ```bash cd libheif mkdir buildjs cd buildjs LIBDE265_VERSION=1.0.16 USE_WASM=0 ../build-emscripten.sh .. # Or build without unsafe-eval LIBDE265_VERSION=1.0.16 USE_UNSAFE_EVAL=0 USE_WASM=0 ../build-emscripten.sh .. ``` -------------------------------- ### Access heic-to with IIFE build via CDN Source: https://github.com/hoppergee/heic-to/blob/main/README.md For use without a package builder, include the IIFE build script from a CDN. The library will be available globally as `HeicTo`. ```html ``` -------------------------------- ### Web Worker for HEIC Conversion (Main Thread) Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/integration-guide.md This JavaScript code demonstrates how to initiate HEIC conversion in a Web Worker from the main thread. It sets up a promise to handle messages and errors from the worker, including a timeout. ```javascript import { heicTo, isHeic } from "heic-to/next" function createImageWorker() { return new Worker(new URL("./image-worker.js", import.meta.url), { type: "module" }) } export async function convertImageInWorker(file) { return new Promise((resolve, reject) => { const worker = createImageWorker() worker.onmessage = (event) => { if (event.data.success) { resolve(event.data.blob) } else { reject(new Error(event.data.error)) } worker.terminate() } worker.onerror = (error) => { reject(error) worker.terminate() } // 30-second timeout const timeout = setTimeout(() => { reject(new Error("Conversion timeout")) worker.terminate() }, 30000) worker.postMessage({ file }, [file.stream().getReader()]) }) } // Usage const file = document.getElementById("fileInput").files[0] try { const blob = await convertImageInWorker(file) const url = URL.createObjectURL(blob) document.getElementById("image").src = url } catch (error) { console.error("Failed to convert:", error) } ``` -------------------------------- ### Worker Initialization Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Ensures the worker is created and available for use by calling an initialization function. ```APIDOC ## Worker Not Created ### Description Troubleshoots the scenario where the worker is not visible in browser developer tools, typically because it's being lazily loaded and has not been initialized yet. ### Solution Call `heicTo()` or `isHeic()` once to trigger the worker's initialization. ```javascript // Call one of these to ensure the worker is created if it hasn't been already // heicTo(someBuffer); // isHeic(someBuffer); ``` ``` -------------------------------- ### Import ESM for Next Build Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Import the necessary functions from the `heic-to/next` package. This is the entry point for using the Web Worker build. ```javascript import { heicTo, isHeic } from "heic-to/next" ``` -------------------------------- ### API Compatibility Between Builds Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Shows that the API for the default and CSP-safe builds of heic-to is identical. You can switch between them by changing the import path. ```javascript // Option 1: Default (requires unsafe-eval) import { heicTo, isHeic } from "heic-to" // Option 2: CSP-safe (no unsafe-eval) import { heicTo, isHeic } from "heic-to/csp" // Same usage either way const blob = await heicTo({ blob: file, type: "image/jpeg" }) ``` -------------------------------- ### Error Handling Pattern in heic-to Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/README.md Demonstrates how to handle potential errors when converting HEIC files using the heicTo function. It includes specific checks for common error messages like 'HEIF image not found' and 'HEIF processing error'. ```javascript try { const blob = await heicTo({ blob: file, type: "image/jpeg", quality: 0.8 }) } catch (error) { if (error === "HEIF image not found") { // File is not a valid HEIF image } else if (error === "HEIF processing error") { // Decoding failed } else if (error === "Can't convert canvas to blob.") { // Encoding failed } else { // Worker or other error } } ``` -------------------------------- ### Type Definitions Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/README.md Lists and explains the key type aliases and interfaces used within the heic-to library, such as ImageMime, HeicTarget, and ImageBitmapOptions. ```APIDOC ## Type Definitions ### Description Defines the custom types and interfaces used throughout the heic-to library. ### Key Types - **`ImageMime`** - **Definition**: A template literal type representing `image/*` MIME types (e.g., `"image/jpeg"`, `"image/png"`). - **Usage**: Constrains string types to valid image MIME formats. - **`HeicTarget`** - **Definition**: A union type representing the possible output formats for `heicTo()`. It can be either a valid `ImageMime` string or the literal string `"bitmap"`. - **Usage**: Specifies the desired output format for the `heicTo()` function. - **`ImageBitmapOptions`** - **Definition**: An interface mirroring the standard `ImageBitmapOptions` used for creating `ImageBitmap` objects. - **Usage**: Provides options for configuring `ImageBitmap` creation within `heicTo()`. ### Standard DOM Types - The library also utilizes standard browser types such as `Blob`, `File`, `ImageBitmap`, and `ImageData`. ``` -------------------------------- ### Lazy Loading heic-to with ESM Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md This snippet demonstrates how to dynamically import the heic-to library using ESM, which is an optimization technique to load the library only when it's needed. ```javascript const { heicTo } = await import("heic-to") ``` -------------------------------- ### Accessing Global Namespace in IIFE Build Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md When using the IIFE build, the library is exposed globally via the `window.HeicTo` object. This is useful for simple HTML pages or when not using a module bundler. ```javascript window.HeicTo // Global namespace ``` -------------------------------- ### Deallocate Resources in Worker Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Shows how to properly deallocate resources, including individual images and the decoder context, to prevent memory leaks, especially within a finally block to ensure execution even on error. ```javascript try { // ... processing ... } finally { // Always free resources, even on error if (data && data.length) { for (let i = 0; i < data.length; i++) { data[i].free(); // Free each image } } if (decoder && decoder.decoder) { libheif.heif_context_free(decoder.decoder); // Free decoder } } ``` -------------------------------- ### Convert HEIC with Fallback to Multiple Formats Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/integration-guide.md Attempts to convert HEIC to JPEG, PNG, and WebP sequentially. Use this when compatibility with various image viewers is crucial. ```javascript import { heicTo, isHeic } from "heic-to" async function convertWithFallback(file) { const formats = [ { type: "image/jpeg", quality: 0.85 }, { type: "image/png" }, { type: "image/webp", quality: 0.85 } ] const isHeicFile = await isHeic(file) if (!isHeicFile) { return { blob: file, format: file.type } } for (const format of formats) { try { const blob = await heicTo({ blob: file, type: format.type, quality: format.quality }) return { blob, format: format.type } } catch (error) { console.warn(`Failed to convert to ${format.type}`) continue } } throw new Error("Failed to convert image in any supported format") } ``` -------------------------------- ### heicTo (CSP Build) Source: https://github.com/hoppergee/heic-to/blob/main/README.md Provides a version of the `heicTo` function that is compatible with Content Security Policy (CSP) restrictions, specifically avoiding `unsafe-eval`. ```APIDOC ## heicTo (CSP Build) ### Description This version of `heicTo` is designed to work within environments with strict Content Security Policy (CSP) settings that disallow `unsafe-eval`. It ensures compatibility by using a different build or import path. ### Method `heicTo(options: { blob: Blob | File, type: "image/jpeg" | "image/png" | "bitmap", quality?: number, options?: object }): Promise` ### Parameters See the main `heicTo` documentation for parameter details. ### Request Example ```javascript // Import from the csp path import { heicTo } from "heic-to/csp" const file = field.files[0] const jpeg = await heicTo({ blob: file, type: "image/jpeg", quality: 0.5 }) ``` ### Response See the main `heicTo` documentation for response details. ``` -------------------------------- ### isHeic() Performance with JPEG Files Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Demonstrates the performance optimization of isHeic(), which reads only 12 bytes for non-HEIC files like JPEGs, resulting in fast detection. ```javascript // For a JPEG file, only reads 12 bytes then returns false const result = await isHeic(jpegFile) // ~1ms ``` -------------------------------- ### Import heicTo for web workers Source: https://github.com/hoppergee/heic-to/blob/main/README.md To use `heicTo` within web workers, import it from 'heic-to/next'. ```diff - import { heicTo } from "heic-to" + import { heicTo } from "heic-to/next" ``` -------------------------------- ### Convert HEIC with Error Handling and Timeout Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/integration-guide.md Handles file size limits, checks for HEIC format, and implements a timeout for the conversion process. Use this for robust client-side conversions. ```javascript import { heicTo, isHeic } from "heic-to" async function convertWithErrorHandling(file, options = {}) { const { maxFileSize = 100 * 1024 * 1024, // 100MB timeout = 30000, quality = 0.85, outputType = "image/jpeg" } = options // Validate file size if (file.size > maxFileSize) { throw new Error(`File is too large (max ${maxFileSize / 1024 / 1024}MB)`) } // Check format const isHeicFile = await isHeic(file) if (!isHeicFile) { return file // Return original if not HEIC } // Convert with timeout return await Promise.race([ heicTo({ blob: file, type: outputType, quality }), new Promise((_, reject) => setTimeout(() => reject(new Error("Conversion timeout")), timeout) ) ]) } // Usage try { const blob = await convertWithErrorHandling(file) console.log("Conversion successful") } catch (error) { if (error.message === "Conversion timeout") { console.error("Conversion took too long") } else if (error.message.includes("too large")) { console.error(error.message) } else { console.error("Conversion failed:", error) } } ``` -------------------------------- ### Default Build CSP Configuration Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/integration-guide.md Configure your Content Security Policy to allow script evaluation for the default build of heic-to. This is required because the worker code is evaluated at runtime. ```http Content-Security-Policy: script-src 'self' 'unsafe-eval'; worker-src blob:; ``` -------------------------------- ### Batch Convert HEIC Files with Progress and Error Handling Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/isheic-detection.md Processes a list of files, converting HEIC files to JPEG and skipping others. It logs progress and collects results for converted, skipped, and failed files. Includes error handling for individual file conversions. ```javascript import { heicTo, isHeic } from "heic-to" async function batchConvertHeic(files) { const results = { converted: [], skipped: [], failed: [] } for (let i = 0; i < files.length; i++) { const file = files[i] try { if (await isHeic(file)) { const blob = await heicTo({ blob: file, type: "image/jpeg", quality: 0.8 }) results.converted.push({ originalFile: file, blob }) console.log(`${i + 1}/${files.length}: Converted ${file.name}`) } else { results.skipped.push(file) console.log(`${i + 1}/${files.length}: Skipped ${file.name} (not HEIC)`) } } catch (error) { results.failed.push({ file, error }) console.error(`${i + 1}/${files.length}: Failed ${file.name}`, error) } } return results }) ``` -------------------------------- ### Use heicTo in a Web Worker Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/heic-to.md Demonstrates how to use heicTo within a web worker for background processing. The main thread sends the file to the worker, and the worker returns the converted bitmap. ```javascript // main thread import { heicTo } from "heic-to/next" const file = document.getElementById("fileInput").files[0] const bitmap = await heicTo({ blob: file, type: "bitmap" }) // worker thread import { heicTo } from "heic-to/next" self.onmessage = async (event) => { const { file } = event.data const bitmap = await heicTo({ blob: file, type: "bitmap" }) self.postMessage({ bitmap }) ``` -------------------------------- ### Lazy Worker Initialization Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/worker-api.md Initializes the web worker only when the first conversion is attempted. This reduces startup time for applications that do not convert images. ```javascript let worker; const loadWorker = () => { if (!worker) { const workerFileContent = WORKER_FILE_CONTENT const workerBlob = new Blob([workerFileContent], {type: 'application/javascript'}) worker = new Worker(URL.createObjectURL(workerBlob)) worker.onerror = (error) => console.error('Worker error:', error) } return worker } ``` -------------------------------- ### ImageBitmapOptions Interface Definition Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/types.md Defines optional parameters for creating an ImageBitmap, including orientation, alpha premultiplication, color space, and resizing options. ```typescript interface ImageBitmapOptions { imageOrientation?: "as-is" | "flipY" premultiplyAlpha?: "default" | "premultiply" | "none" colorSpaceConversion?: "default" | "none" resizeWidth?: unsigned long resizeHeight?: unsigned long resizeQuality?: "pixelated" | "low" | "medium" | "high" } ``` -------------------------------- ### Convert HEIC to Multiple Formats Simultaneously Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/heic-to.md Converts a single HEIC file to multiple image formats (JPEG, PNG, WebP) concurrently using Promise.all. This is efficient for generating various output types from one source. ```javascript import { heicTo, isHeic } from "heic-to" const file = document.getElementById("fileInput").files[0] if (await isHeic(file)) { const [jpeg, png, webp] = await Promise.all([ heicTo({ blob: file, type: "image/jpeg", quality: 0.8 }), heicTo({ blob: file, type: "image/png" }), heicTo({ blob: file, type: "image/webp", quality: 0.8 }) ]) console.log("JPEG size:", jpeg.size) console.log("PNG size:", png.size) console.log("WebP size:", webp.size) } ``` -------------------------------- ### Canvas Element Difference Source: https://github.com/hoppergee/heic-to/blob/main/_autodocs/api-reference/build-variants.md Illustrates the difference in canvas element creation between the default build and the Next/Worker build. The worker build uses OffscreenCanvas for thread safety. ```javascript // Default build (src/index.js:66) const canvas = document.createElement('canvas') ``` ```javascript // Next/Worker build (src/next/index.js:66) const canvas = new OffscreenCanvas(imageData.width, imageData.height) ```