### Installation and Basic Usage Source: https://github.com/lokesh/color-thief/blob/master/README.md Instructions on how to install Color Thief and a quick start guide with examples for extracting dominant colors and palettes. ```APIDOC ## Installation Install via npm: ```bash npm install colorthief ``` Or use a CDN: ```html ``` ## Quick Start ### Dominant Color ```js import { getColorSync } from 'colorthief'; const img = document.querySelector('img'); const color = getColorSync(img); console.log(color.hex()); // '#e84393' console.log(color.css()); // 'rgb(232, 67, 147)' console.log(color.isDark); // false console.log(color.textColor); // '#000000' ``` ### Color Palette ```js import { getPaletteSync } from 'colorthief'; const img = document.querySelector('img'); const palette = getPaletteSync(img, { colorCount: 6 }); palette.forEach(c => console.log(c.hex())); ``` ### Semantic Swatches ```js import { getSwatches } from 'colorthief'; const img = document.querySelector('img'); const swatches = await getSwatches(img); console.log(swatches.Vibrant?.color.hex()); ``` ``` -------------------------------- ### Color Thief Installation Source: https://context7.com/lokesh/color-thief/llms.txt Instructions on how to install the Color Thief library using npm or a CDN. ```APIDOC ## Installation Install using npm: ```bash npm install colorthief ``` Or load from a CDN: ```html ``` ``` -------------------------------- ### CLI Usage Examples Source: https://context7.com/lokesh/color-thief/llms.txt Examples of how to use the Color Thief CLI for various image processing tasks. ```APIDOC ## CLI Usage Examples ### CSS Custom Properties Output ```bash colorthief-cli palette photo.jpg --css ``` ### Configure Extraction Options ```bash colorthief-cli palette photo.jpg --count 5 --quality 1 --color-space oklch ``` ### Process from Standard Input ```bash cat photo.jpg | colorthief-cli - curl -s https://example.com/image.jpg | colorthief-cli - ``` ### Process Multiple Files ```bash colorthief-cli photo1.jpg photo2.jpg photo3.jpg --json ``` ``` -------------------------------- ### Quick Start: Get Dominant Color and Palette Source: https://github.com/lokesh/color-thief/blob/master/README.md Demonstrates how to import and use synchronous functions to get the dominant color and a color palette from an image element. ```javascript import { getColorSync, getPaletteSync, getSwatches } from 'colorthief'; // Dominant color const color = getColorSync(img); color.hex(); // '#e84393' color.css(); // 'rgb(232, 67, 147)' color.isDark; // false color.textColor; // '#000000' // Palette const palette = getPaletteSync(img, { colorCount: 6 }); palette.forEach(c => console.log(c.hex())); // Semantic swatches (Vibrant, Muted, DarkVibrant, etc.) const swatches = await getSwatches(img); swatches.Vibrant?.color.hex(); ``` -------------------------------- ### Install Color Thief via npm Source: https://github.com/lokesh/color-thief/blob/master/README.md Use npm to install the Color Thief library for your project. ```bash npm install colorthief ``` -------------------------------- ### Quick Start CLI Command Source: https://github.com/lokesh/color-thief/blob/master/README.md Execute the colorthief-cli tool directly using npx for quick dominant color extraction from an image. ```bash npx colorthief-cli photo.jpg ``` -------------------------------- ### Browser: Live Color Palette Updates with observe() Source: https://github.com/lokesh/color-thief/blob/master/README.md Utilize the `observe` function to watch video, canvas, or image elements and receive palette updates reactively. This example shows how to update ambient lighting based on video content. ```javascript import { observe } from 'colorthief'; // Watch a video and update ambient lighting as it plays const controller = observe(videoElement, { throttle: 200, // ms between updates colorCount: 5, onChange(palette) { updateAmbientBackground(palette); }, }); // Stop when done controller.stop(); ``` -------------------------------- ### Getting a color palette (sync, browser) Source: https://github.com/lokesh/color-thief/blob/master/V3.md Use the synchronous `getPaletteSync` function in the browser. Specify `colorCount` and `quality` as options. ```javascript getPaletteSync(img, { colorCount: 8 }) ``` ```javascript getPaletteSync(img, { colorCount: 8, quality: 5 }) ``` -------------------------------- ### Getting a color palette (async) Source: https://github.com/lokesh/color-thief/blob/master/V3.md Use the asynchronous `getPalette` function with an image element. Specify `colorCount` and `quality` as options. ```javascript await getPalette(img, { colorCount: 8 }) ``` ```javascript await getPalette(img, { colorCount: 8, quality: 5 }) ``` -------------------------------- ### Example of Rich Color Output Object Source: https://github.com/lokesh/color-thief/blob/master/PLAN.md Demonstrates the new rich color object format with methods for different color spaces and properties like isDark. This replaces the previous bare [r, g, b] array output. ```javascript const color = await colorThief.getColor(image); color.rgb() // { r, g, b } color.hex() // '#e84d3d' color.hsl() // { h, s, l } color.oklch() // { l, c, h } color.array() // [r, g, b] (backward-compat escape hatch) color.isDark // boolean ``` -------------------------------- ### Browser: Get Dominant Color and Palette Synchronously Source: https://github.com/lokesh/color-thief/blob/master/README.md Example of using synchronous functions to extract the dominant color and a palette from an image element in the browser. ```javascript import { getColorSync, getPaletteSync } from 'colorthief'; const img = document.querySelector('img'); const color = getColorSync(img); console.log(color.hex()); const palette = getPaletteSync(img, { colorCount: 5 }); ``` -------------------------------- ### Dynamic Theming with Accessibility Source: https://context7.com/lokesh/color-thief/llms.txt Example of using the Color object to dynamically set background and text colors for UI elements, including accessibility checks for contrast ratios. This ensures readable text on varying backgrounds. ```javascript // Usage example const color = palette[0]; // Dynamic theming with accessibility const bgColor = color.hex(); const textColor = color.textColor; const contrastWithWhite = color.contrast.white; element.style.backgroundColor = bgColor; element.style.color = textColor; if (contrastWithWhite >= 4.5) { console.log('Meets WCAG AA for normal text on white'); } if (contrastWithWhite >= 7) { console.log('Meets WCAG AAA for normal text on white'); } ``` -------------------------------- ### Getting Text Color Recommendations Per Swatch Source: https://github.com/lokesh/color-thief/blob/master/V3.md The getSwatches function now returns text color recommendations for each swatch, simplifying the creation of accessible UIs with colored elements and readable text. ```typescript const swatches = await getSwatches(img); swatches.forEach(swatch => { const swatchColor = swatch.hex(); const textColor = swatch.suggestedTextColors.darkText; // or .lightText console.log(`Swatch: ${swatchColor}, Text Color: ${textColor}`); }); ``` -------------------------------- ### Getting WCAG Contrast Ratios and Text Color Source: https://github.com/lokesh/color-thief/blob/master/V3.md Access WCAG contrast ratios and suggested foreground colors directly from Color objects for building accessible UIs. ```typescript const color = await getColor(img); console.log('WCAG Contrast:', color.contrast); console.log('Suggested Text Color:', color.suggestedTextColors); // Example usage in UI: const cardStyle = { backgroundColor: color.hex(), color: color.suggestedTextColors.darkText // or .lightText }; ``` -------------------------------- ### Getting color from URL (v2) Source: https://github.com/lokesh/color-thief/blob/master/V3.md This is the v2 method for getting a color directly from a URL using a callback. ```javascript ct.getColorFromUrl(url, cb) ``` -------------------------------- ### Getting a single color (sync, browser) Source: https://github.com/lokesh/color-thief/blob/master/V3.md Use the synchronous `getColorSync` function in the browser. Quality can be specified as an option. ```javascript getColorSync(img) ``` ```javascript getColorSync(img, { quality: 5 }) ``` -------------------------------- ### Getting color from URL (v3) Source: https://github.com/lokesh/color-thief/blob/master/V3.md In v3, you must load the image yourself first and then use the `getColor` function. This applies to both async and sync browser usage. ```javascript await getColor(img) ``` ```javascript getColorSync(img) ``` -------------------------------- ### Getting color with CommonJS (v2) Source: https://github.com/lokesh/color-thief/blob/master/V3.md This shows the v2 method of getting a color using `require` in a CommonJS environment. ```javascript require('colorthief').getColor(path) ``` -------------------------------- ### Get Dominant Color and Palette in Node.js Source: https://github.com/lokesh/color-thief/blob/master/README.md Import and use `getColor` and `getPalette` functions from the 'colorthief' package. Accepts file paths or Buffers. Requires 'sharp' for image decoding. ```javascript import { getColor, getPalette } from 'colorthief'; const color = await getColor('/path/to/image.jpg'); console.log(color.hex()); const palette = await getPalette(Buffer.from(data), { colorCount: 5 }); ``` -------------------------------- ### Get semantic color swatches synchronously Source: https://github.com/lokesh/color-thief/blob/master/index.html Use getSwatchesSync to classify palette colors into semantic roles like Vibrant, Muted, and DarkVibrant. Each swatch provides text color recommendations. ```javascript const swatches = getSwatchesSync(img); swatches.Vibrant?.color.hex(); // '#e84393' swatches.DarkMuted?.titleTextColor.hex(); // '#ffffff' ``` -------------------------------- ### CLI Options for Palette Generation Source: https://github.com/lokesh/color-thief/blob/master/README.md Illustrates CLI options for customizing palette generation, such as specifying the number of colors, sampling quality, and color space. ```bash colorthief-cli palette photo.jpg --count 5 # Number of colors (2-20) colorthief-cli photo.jpg --quality 1 # Sampling quality (1=best) colorthief-cli photo.jpg --color-space rgb # Color space (rgb or oklch) ``` -------------------------------- ### Releasing Commands Source: https://github.com/lokesh/color-thief/blob/master/README.md Outlines the steps for releasing a new version of the library, including running tests, versioning, and publishing to npm. ```bash # 1. Make sure you're on master with a clean working tree git status # 2. Run the full test suite npm run build npm run test:node npm run test:browser # requires npm run dev in another terminal # 3. Preview what will be published npm pack --dry-run # 4. Tag and publish npm version # bumps version, creates git tag npm publish # builds via prepublishOnly, then publishes git push && git push --tags ``` -------------------------------- ### Build and Test Commands Source: https://github.com/lokesh/color-thief/blob/master/README.md Provides npm scripts for building the project's distribution formats and running various test suites. ```bash npm run build # Build all dist formats npm run test # Run all tests (Mocha + Cypress) npm run test:node # Node tests only npm run test:browser # Browser tests (requires npm run dev) npm run dev # Start local server on port 8080 ``` -------------------------------- ### Getting a single color (async) Source: https://github.com/lokesh/color-thief/blob/master/V3.md Use the asynchronous `getColor` function with an image element. Quality can be specified as an option. ```javascript await getColor(img) ``` ```javascript await getColor(img, { quality: 5 }) ``` -------------------------------- ### Using Custom Pixel Loaders Source: https://github.com/lokesh/color-thief/blob/master/V3.md Integrate a custom pixel loader, such as one using '@napi-rs/image' or 'jimp', for image decoding instead of the default sharp implementation. ```typescript import { configure } from 'colorthief'; import { customImageLoader } from './custom-loaders'; configure({ loader: customImageLoader }); ``` -------------------------------- ### Pluggable Architecture with configure() Source: https://github.com/lokesh/color-thief/blob/master/V3.md Configure global quantizers and loaders, or override them per-call. This allows for custom implementations of PixelLoader and Quantizer. ```typescript import { configure, getPalette } from 'colorthief'; import { WasmQuantizer, createNodeLoader } from 'colorthief/internals'; // Global: swap the quantizer for all calls const q = new WasmQuantizer(); await q.init(); configure({ quantizer: q }); // Global: swap the pixel loader for all calls configure({ loader: createNodeLoader({ decoder: myCustomDecoder }) }); // Per-call: override for just this extraction const palette = await getPalette(img, { quantizer: someOtherQuantizer }); ``` -------------------------------- ### Extract Dominant Color (Async) - Node.js Source: https://context7.com/lokesh/color-thief/llms.txt Get the single dominant color from an image file path or Buffer asynchronously in Node.js. ```javascript import { getColor } from 'colorthief'; // Node.js usage with file path const nodeColor = await getColor('/path/to/image.jpg'); console.log(nodeColor.hex()); // Node.js usage with Buffer import { readFileSync } from 'fs'; const buffer = readFileSync('/path/to/image.png'); const bufferColor = await getColor(buffer); console.log(bufferColor.hex()); ``` -------------------------------- ### Color Space Option Source: https://github.com/lokesh/color-thief/blob/master/index.html Demonstrates how to specify the color space for palette quantization. ```APIDOC ## OKLCH vs RGB Quantization OKLCH quantization produces more perceptually uniform palettes. Colors that "feel" evenly spaced to the human eye. ### Method `getPaletteSync(img, { colorCount: number, colorSpace: 'rgb' | 'oklch' })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Default — quantize in sRGB const rgb = getPaletteSync(img, { colorCount: 8 }); // Perceptual — quantize in OKLCH const oklch = getPaletteSync(img, { colorCount: 8, colorSpace: 'oklch' }); ``` ### Response #### Success Response (200) - **palette** (Array) - An array of Color objects representing the extracted palette. #### Response Example ```json [ { "hex": "#e84393" }, { "hex": "#f08080" }, { "hex": "#20b2aa" } ] ``` ``` -------------------------------- ### Configurable Pixel Filtering Options Source: https://github.com/lokesh/color-thief/blob/master/PLAN.md Shows how to pass an options object to `getColor` to configure pixel filtering, including ignoring white pixels, alpha threshold, and minimum saturation. Existing positional arguments for quality and color count are still supported for backward compatibility. ```javascript getColor(image, { quality: 10, ignoreWhite: false }) ``` -------------------------------- ### Get Color from Same Domain Image URL Source: https://github.com/lokesh/color-thief/blob/master/async.html Use `getColorFromUrl` for same-domain images. This method is synchronous and requires a callback function to handle the extracted color. ```javascript var colorThief = new ColorThief(); colorSync = colorThief.getColorFromUrl("examples/img/image-1.jpg", function(color){ $('#samedomain').css('background-color','rgb('+color[0]+','+color[1]+','+color[2]+')') console.log('url',color) }); ``` -------------------------------- ### Options and Color Object Source: https://github.com/lokesh/color-thief/blob/master/README.md Explanation of available options for API functions and the properties/methods of the returned Color objects. ```APIDOC ## Options | Option | Default | Description | |---|---|---| | `colorCount` | `10` | Number of palette colors (2–20) | | `quality` | `10` | Sampling rate (1 = every pixel, 10 = every 10th) | | `colorSpace` | `'oklch'` | Quantization space: `'rgb'` or `'oklch'` | | `worker` | `false` | Offload to Web Worker (browser only) | | `signal` | — | `AbortSignal` to cancel extraction | | `ignoreWhite` | `true` | Skip white pixels | ## Color Object | Property / Method | Returns | |---|---| | `.rgb()` | `{ r, g, b }` | | `.hex()` | `'#ff8000'` | | `.hsl()` | `{ h, s, l }` | | `.oklch()` | `{ l, c, h }` | | `.css(format?)` | `'rgb(255, 128, 0)'`, `'hsl(…)'`, or `'oklch(…)'` | | `.array()` | `[r, g, b]` | | `.toString()` | Hex string (works in template literals) | | `.textColor` | `'#ffffff'` or `'#000000'` | | `.isDark` / `.isLight` | Boolean | | `.contrast` | `{ white, black, foreground }` — WCAG ratios | | `.population` | Raw pixel count | | `.proportion` | 0–1 share of total | ``` -------------------------------- ### Get multi-color palette synchronously Source: https://github.com/lokesh/color-thief/blob/master/index.html Use getPaletteSync to extract a multi-color palette from an image synchronously. Specify the desired number of colors using the colorCount option. ```javascript const palette = getPaletteSync(img, { colorCount: 8 }); palette.forEach(c => console.log(c.hex())); ``` -------------------------------- ### CLI Input via Stdin Source: https://github.com/lokesh/color-thief/blob/master/README.md Demonstrates how to pipe image data directly to the color thief CLI using standard input. ```bash cat photo.jpg | colorthief-cli - ``` -------------------------------- ### Get Color from Cross-Domain Image URL Source: https://github.com/lokesh/color-thief/blob/master/async.html Use `getColorAsync` for cross-domain images. This method is asynchronous and accepts a callback function that receives the color and the image element. ```javascript colorThief.getColorAsync("https://lokeshdhakar.com/media/posts/color-thief/color-thief-pixels.png",function(color, element){ $('#crossdomain').css('background-color','rgb('+color[0]+','+color[1]+','+color[2]+')') $('#crossdomain img').attr('src',element.src) console.log('async', color, element.src) }); ``` -------------------------------- ### Get Semantic Swatches Synchronously Source: https://github.com/lokesh/color-thief/blob/master/index.html Extracts semantically distinct swatches (e.g., Vibrant, Muted) from an image synchronously using `getSwatchesSync`. Displays cards for each swatch role. ```javascript { const { result: swatches, ms } = timed(() => getSwatchesSync(img2)); const roles = ['Vibrant', 'Muted', 'DarkVibrant', 'DarkMuted', 'LightVibrant', 'LightMuted']; document.getElementById('swatch-cards').innerHTML = roles.map(role => { const s = swatches[role]; if (!s) { return `
${role}
`; } return `
` }).join(''); } ``` -------------------------------- ### Enable OKLCH Quantization Source: https://github.com/lokesh/color-thief/blob/master/PLAN.md Opt-in to perform color quantization in the OKLCH color space for more perceptually distinct palettes. Default remains RGB. ```javascript getColor(image, { quantization: 'oklch' }) ``` -------------------------------- ### CLI: Configure Extraction Options Source: https://context7.com/lokesh/color-thief/llms.txt Configure the CLI for color extraction by specifying the number of colors, quality, and color space. Adjust these options for different use cases. ```bash colorthief-cli palette photo.jpg --count 5 --quality 1 --color-space oklch ``` -------------------------------- ### Get Dominant Color Synchronously Source: https://github.com/lokesh/color-thief/blob/master/index.html Extracts the dominant color from an image synchronously using `getColorSync`. Displays the color swatch, hex code, RGB values, and execution time. ```javascript { [ [img1, 'dom-result-1'], [img2, 'dom-result-2'], [img3, 'dom-result-3'], ].forEach(([img, id]) => { const { result: color, ms } = timed(() => getColorSync(img)); if (!color) return; const { r, g, b } = color.rgb(); document.getElementById(id).innerHTML = swatchHTML(color, 'lg') + `
${color.hex()}
rgb(${r}, ${g}, ${b}) ${ms}ms
`; }); show('out-dominant'); } ``` -------------------------------- ### Per-Call Quantizer and Loader Configuration Source: https://github.com/lokesh/color-thief/blob/master/V3.md Configure the quantizer and loader on a per-call basis, which takes priority over global configurations. This is useful for specific extractions requiring different settings. ```typescript import { getPalette } from 'colorthief'; import { WasmQuantizer } from 'colorthief/internals'; const q = new WasmQuantizer(); await q.init(); // Use WASM quantizer for just this call: const palette = await getPalette(img, { quantizer: q, colorCount: 10 }); ``` -------------------------------- ### Get Dominant Color from Image Source: https://github.com/lokesh/color-thief/blob/master/cypress/test-pages/es6-module.html Use `getColorSync` to extract the dominant color from an image element. Ensure the image is loaded before processing. The result is displayed as an RGB array string. ```javascript import { getColorSync } from '../../dist/index.js'; const image = document.querySelector('img'); function getColorFromImage(img) { const result = getColorSync(img); document.querySelector('#result').innerText = result ? result.array().toString() : 'null'; } if (image.complete) { getColorFromImage(image); } else { image.addEventListener('load', function() { getColorFromImage(image); }); } ``` -------------------------------- ### CLI - Command Line Interface Source: https://context7.com/lokesh/color-thief/llms.txt Extract colors from images via the command line with JSON, CSS, and ANSI output formats. ```APIDOC ## CLI - Command Line Interface Extract colors from images via the command line with JSON, CSS, and ANSI output formats. ### Installation ```bash npx colorthief-cli photo.jpg # Or install globally npm install -g colorthief-cli ``` ### Usage - **Dominant color (default):** ```bash colorthief-cli photo.jpg # Output: ▇▇ #e84393 ``` - **Color palette:** ```bash colorthief-cli palette photo.jpg # Output: # ▇▇ #e84393 # ▇▇ #6c5ce7 # ▇▇ #00b894 # ... ``` - **Semantic swatches:** ```bash colorthief-cli swatches photo.jpg # Output: # Vibrant ▇▇ #e84393 # Muted ▇▇ #a29bfe # DarkVibrant ▇▇ #6c5ce7 # ... ``` - **JSON output:** ```bash colorthief-cli photo.jpg --json # { # "hex": "#e84393", # "rgb": { "r": 232, "g": 67, "b": 147 }, # ... # } ``` ``` -------------------------------- ### Image Color Palette Extraction with Quality Settings Source: https://github.com/lokesh/color-thief/blob/master/index.html Demonstrates how the 'quality' option affects the time and result of color palette extraction. Lower quality values are faster but may yield less accurate palettes. ```javascript const quals = [1, 10, 50]; const container = document.getElementById('out-quality'); container.insertAdjacentHTML('beforeend', quals.map(q => { const { result: pal, ms } = timed(() => getPaletteSync(img1, { colorCount: 6, quality: q })); return `
quality: ${q} ${ms}ms
${pal ? pal.map(c => swatchHTML(c, 'md')).join('') : ''}
`; }).join('')); show('out-quality'); ``` -------------------------------- ### Extract Dominant Color (Async) - Browser Source: https://context7.com/lokesh/color-thief/llms.txt Get the single dominant color from an image element asynchronously in the browser. The returned Color object provides various formats and accessibility information. ```javascript import { getColor } from 'colorthief'; // Browser usage with image element const img = document.querySelector('img'); const color = await getColor(img); console.log(color.hex()); // '#e84393' console.log(color.rgb()); // { r: 232, g: 67, b: 147 } console.log(color.hsl()); // { h: 330, s: 78, l: 59 } console.log(color.oklch()); // { l: 0.65, c: 0.22, h: 0.5 } console.log(color.css()); // 'rgb(232, 67, 147)' console.log(color.css('hsl')); // 'hsl(330, 78%, 59%)' console.log(color.css('oklch')); // 'oklch(0.650 0.220 0.5)' console.log(color.isDark); // false console.log(color.textColor); // '#000000' (readable text color for this background) console.log(color.contrast); // { white: 3.2, black: 6.5, foreground: Color } ``` -------------------------------- ### Global Configuration for Color-Thief Source: https://context7.com/lokesh/color-thief/llms.txt Override the default pixel loader and/or quantizer globally for all subsequent `getPalette` calls. This is useful for integrating custom image decoders or using the optional WASM quantizer for improved performance. Per-call options take precedence over global configuration. ```javascript import { configure, getPalette } from 'colorthief'; import { WasmQuantizer } from 'colorthief/internals'; // Initialize and configure WASM quantizer for ~6x faster quantization const wasmQuantizer = new WasmQuantizer(); await wasmQuantizer.init(); configure({ quantizer: wasmQuantizer }); // All subsequent calls use WASM quantizer const palette = await getPalette(img, { colorCount: 10 }); // Configure custom pixel loader configure({ loader: { async load(source, signal) { // Custom image decoding logic // Must return { data: Uint8Array, width: number, height: number } const imageData = await myCustomDecoder(source); return imageData; } } }); // Per-call override (takes priority over configure()) const paletteWithCustomQuantizer = await getPalette(img, { quantizer: myCustomQuantizer, loader: myCustomLoader, }); ``` -------------------------------- ### Color Object Properties Source: https://github.com/lokesh/color-thief/blob/master/index.html Demonstrates creating a Color object from a dominant color and displaying its properties, including a preview swatch, hex code, and a detailed property table. ```javascript { const color = getColorSync(img1); if (color) { document.getElementById('color-preview').innerHTML = `
Aa
${color.hex()}
`; renderColorTable(color, 'prop-table'); } show('out-color-obj'); } ``` -------------------------------- ### Progressive Color Extraction Source: https://github.com/lokesh/color-thief/blob/master/PLAN.md For large images, use the progressive option to get an approximate palette immediately from a downsampled pass, with results refined over time. This returns an async iterator or observable. ```javascript getColor(image, { progressive: true }) ``` -------------------------------- ### configure - Global Configuration Source: https://context7.com/lokesh/color-thief/llms.txt Override the default pixel loader and/or quantizer globally. This is useful for using custom image decoders or the optional WASM quantizer for better performance. ```APIDOC ## configure - Global Configuration Override the default pixel loader and/or quantizer globally. Useful for using custom image decoders or the optional WASM quantizer for better performance. ### Parameters - **options** (object) - Configuration options: - **quantizer** (object) - A custom quantizer object with an `init` and `quantize` method. - **loader** (object) - A custom loader object with a `load` method. ### Example ```javascript import { configure, getPalette } from 'colorthief'; import { WasmQuantizer } from 'colorthief/internals'; // Configure WASM quantizer const wasmQuantizer = new WasmQuantizer(); await wasmQuantizer.init(); configure({ quantizer: wasmQuantizer }); // Subsequent calls use WASM quantizer const palette = await getPalette(img, { colorCount: 10 }); // Configure custom pixel loader configure({ loader: { async load(source, signal) { const imageData = await myCustomDecoder(source); return imageData; } } }); // Per-call override const paletteWithCustomQuantizer = await getPalette(img, { quantizer: myCustomQuantizer, loader: myCustomLoader, }); ``` ``` -------------------------------- ### Extract Color Palette (Async) - Basic Usage Source: https://context7.com/lokesh/color-thief/llms.txt Get a color palette from an image asynchronously, specifying the desired number of colors. The returned palette is an array of Color objects sorted by prominence. ```javascript import { getPalette } from 'colorthief'; // Basic usage const img = document.querySelector('img'); const palette = await getPalette(img, { colorCount: 6 }); palette.forEach((color, index) => { console.log(`Color ${index + 1}:`); console.log(` Hex: ${color.hex()}`); console.log(` Population: ${color.population}`); console.log(` Proportion: ${(color.proportion * 100).toFixed(1)}%`); console.log(` Text color: ${color.textColor}`); }); ``` -------------------------------- ### Web Worker Offloading for Quantization Source: https://github.com/lokesh/color-thief/blob/master/V3.md Offload the quantization step to a Web Worker for improved performance. The library handles worker management, message tracking, and cleanup. ```typescript const palette = await getPalette(img, { worker: true }); ``` -------------------------------- ### Color-Thief CLI Usage Source: https://context7.com/lokesh/color-thief/llms.txt Extract colors from images directly from the command line. Supports JSON, CSS, and ANSI output formats for easy integration into scripts and workflows. Install via npm or npx. ```bash # Install CLI npx colorthief-cli photo.jpg # Or install globally npm install -g colorthief-cli # Extract dominant color (default command) colorthief-cli photo.jpg # Output: ▇▇ #e84393 # Extract color palette colorthief-cli palette photo.jpg # Output: # ▇▇ #e84393 # ▇▇ #6c5ce7 # ▇▇ #00b894 # ... # Extract semantic swatches colorthief-cli swatches photo.jpg # Output: # Vibrant ▇▇ #e84393 # Muted ▇▇ #a29bfe # DarkVibrant ▇▇ #6c5ce7 # ... # JSON output for scripting colorthief-cli photo.jpg --json # { # "hex": "#e84393", # "rgb": { "r": 232, "g": 67, "b": 147 }, # } ``` -------------------------------- ### Get Dominant Color from Image (JavaScript) Source: https://github.com/lokesh/color-thief/blob/master/cypress/test-pages/cors.html Use this function to extract the dominant color from an image element. It handles cases where the image might not be fully loaded yet. Requires the ColorThief library to be included. ```javascript const img = document.querySelector('img'); function getColorFromImage(img) { const result = ColorThief.getColorSync(img); document.querySelector('#result').innerText = result ? result.array().toString() : 'null'; } if (img.complete) { getColorFromImage(img); } else { img.addEventListener('load', function() { getColorFromImage(img); }); } ``` -------------------------------- ### getSwatches - Extract Semantic Swatches (Async) Source: https://context7.com/lokesh/color-thief/llms.txt Extracts semantic swatches from an image asynchronously, classifying them into UI roles like Vibrant, Muted, DarkVibrant, etc. Each swatch includes accessibility-focused text color recommendations. ```APIDOC ## getSwatches - Extract Semantic Swatches (Async) ### Description Get semantic swatches classified into UI roles: Vibrant, Muted, DarkVibrant, DarkMuted, LightVibrant, and LightMuted. Each swatch includes accessibility-focused text color recommendations using OKLCH-based classification. ### Method Async Function ### Endpoint N/A (Client-side JavaScript library) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { getSwatches } from 'colorthief'; const img = document.querySelector('img'); const swatches = await getSwatches(img); // Access each swatch role console.log(swatches.Vibrant?.color.hex()); // Most saturated mid-tone console.log(swatches.Muted?.color.hex()); // Desaturated mid-tone console.log(swatches.DarkVibrant?.color.hex()); // Saturated dark color console.log(swatches.DarkMuted?.color.hex()); // Desaturated dark color console.log(swatches.LightVibrant?.color.hex()); // Saturated light color console.log(swatches.LightMuted?.color.hex()); // Desaturated light color // Each swatch includes text color recommendations const vibrant = swatches.Vibrant; if (vibrant) { console.log('Background:', vibrant.color.hex()); console.log('Title text:', vibrant.titleTextColor.hex()); console.log('Body text:', vibrant.bodyTextColor.hex()); console.log('Role:', vibrant.role); } // Apply swatches to theming if (swatches.Vibrant) { document.documentElement.style.setProperty('--primary', swatches.Vibrant.color.hex()); } if (swatches.DarkMuted) { document.documentElement.style.setProperty('--background', swatches.DarkMuted.color.hex()); } if (swatches.LightVibrant) { document.documentElement.style.setProperty('--accent', swatches.LightVibrant.color.hex()); } ``` ### Response #### Success Response (200) An object containing various semantic swatches (e.g., Vibrant, Muted) and their associated text color recommendations. #### Response Example ```json { "Vibrant": { "color": {"hex": "#ff0000"}, "titleTextColor": {"hex": "#ffffff"}, "bodyTextColor": {"hex": "#eeeeee"}, "role": "Vibrant" }, "Muted": { "color": {"hex": "#808080"}, "titleTextColor": {"hex": "#ffffff"}, "bodyTextColor": {"hex": "#dddddd"}, "role": "Muted" } // ... other swatches } ``` ``` -------------------------------- ### Web Worker Offloading for Quantization Source: https://github.com/lokesh/color-thief/blob/master/V3.md Move the quantization computation off the main thread entirely by utilizing Web Workers. This eliminates UI jank, regardless of image size. ```javascript // Assuming 'colorthief.js' is bundled for the browser and supports workers import ColorThief from 'colorthief/dist/color-thief.umd.js'; const thief = new ColorThief(); // The library internally handles worker offloading if available // Example usage remains similar, but computation is off main thread thief.getPalette(img).then(palette => { console.log(palette); }).catch(err => { console.error(err); }); ``` -------------------------------- ### Using Color Objects with Array Method Source: https://github.com/lokesh/color-thief/blob/master/V3.md v3 returns Color objects instead of arrays. Use the .array() method to get the v2-style RGB tuple if needed for existing code that destructures or indexes the result. ```typescript const color = await getColor(img); const rgbArray = color.array(); // For v2-style tuple ``` -------------------------------- ### Creating a Color Object Source: https://github.com/lokesh/color-thief/blob/master/index.html Shows how to create a Color object directly using its RGBA values. This is useful when you have color data and want to leverage Color Thief's color manipulation methods. ```javascript const color = createColor(232, 67, 147, 1); document.getElementById('create-preview').innerHTML = `
Aa
${color.hex()}
`; renderColorTable(color, 'create-table'); show('out-create'); ``` -------------------------------- ### Opt-in Web Worker Usage Source: https://github.com/lokesh/color-thief/blob/master/PLAN.md Illustrates how to enable Web Worker support for offloading image processing tasks from the main thread. This is an opt-in feature via the configuration object. ```javascript getColor(image, { worker: true }) ``` -------------------------------- ### Formatting color as hex Source: https://github.com/lokesh/color-thief/blob/master/V3.md v3 offers a `hex()` method for easy hex color string conversion, simplifying the manual mapping used in v2. ```javascript color.hex() ``` ```javascript color.toString() ``` -------------------------------- ### CLI Commands for Color Extraction Source: https://github.com/lokesh/color-thief/blob/master/README.md Demonstrates basic color thief CLI commands for extracting the dominant color, a color palette, and semantic swatches from an image. ```bash # Dominant color colorthief-cli photo.jpg # Color palette colorthief-cli palette photo.jpg # Semantic swatches colorthief-cli swatches photo.jpg ``` -------------------------------- ### Compare OKLCH and sRGB quantization Source: https://github.com/lokesh/color-thief/blob/master/index.html Compare palettes generated using default sRGB quantization versus perceptual OKLCH quantization. OKLCH aims for more perceptually uniform color spacing. ```javascript // Default — quantize in sRGB const rgb = getPaletteSync(img, { colorCount: 8 }); // Perceptual — quantize in OKLCH const oklch = getPaletteSync(img, { colorCount: 8, colorSpace: 'oklch' }); ``` -------------------------------- ### CLI Output Formats Source: https://github.com/lokesh/color-thief/blob/master/README.md Showcases different output formats for the color thief CLI, including ANSI swatches, JSON, and CSS custom properties. ```bash # Default: ANSI color swatches colorthief-cli photo.jpg # ▇▇ #e84393 # JSON with full color data colorthief-cli photo.jpg --json # CSS custom properties colorthief-cli palette photo.jpg --css # :root { # --color-1: #e84393; # --color-2: #6c5ce7; # } ``` -------------------------------- ### Extract Semantic Swatches (Async) Source: https://context7.com/lokesh/color-thief/llms.txt Use getSwatches for asynchronous extraction of semantic color swatches, including UI roles and accessibility-focused text color recommendations. Access individual swatch roles like Vibrant, Muted, and their variants. ```javascript import { getSwatches } from 'colorthief'; const img = document.querySelector('img'); const swatches = await getSwatches(img); // Access each swatch role console.log(swatches.Vibrant?.color.hex()); // Most saturated mid-tone console.log(swatches.Muted?.color.hex()); // Desaturated mid-tone console.log(swatches.DarkVibrant?.color.hex()); // Saturated dark color console.log(swatches.DarkMuted?.color.hex()); // Desaturated dark color console.log(swatches.LightVibrant?.color.hex()); // Saturated light color console.log(swatches.LightMuted?.color.hex()); // Desaturated light color // Each swatch includes text color recommendations const vibrant = swatches.Vibrant; if (vibrant) { console.log('Background:', vibrant.color.hex()); console.log('Title text:', vibrant.titleTextColor.hex()); console.log('Body text:', vibrant.bodyTextColor.hex()); console.log('Role:', vibrant.role); } // Apply swatches to theming if (swatches.Vibrant) { document.documentElement.style.setProperty('--primary', swatches.Vibrant.color.hex()); } if (swatches.DarkMuted) { document.documentElement.style.setProperty('--background', swatches.DarkMuted.color.hex()); } if (swatches.LightVibrant) { document.documentElement.style.setProperty('--accent', swatches.LightVibrant.color.hex()); } ``` -------------------------------- ### Import Main API Functions from Color Thief Source: https://github.com/lokesh/color-thief/blob/master/V3.md Import the primary functions for color extraction and palette generation from the main entry point of the Color Thief package. ```typescript import { getColor, getPalette, getSwatches, createColor } from 'colorthief'; ``` -------------------------------- ### createColor() - Manual Color Creation Source: https://github.com/lokesh/color-thief/blob/master/index.html Manually construct a Color object from RGB values. This is useful for programmatically creating colors or when working with known color values. ```APIDOC ## createColor() ### Description Build a Color object manually from RGB values. Useful for creating colors programmatically or working with known values. ### Method `createColor(r, g, b, a)` ### Parameters #### Path Parameters - **r** (number) - Required - Red component (0-255). - **g** (number) - Required - Green component (0-255). - **b** (number) - Required - Blue component (0-255). - **a** (number) - Optional - Alpha component (0-1). Defaults to 1. ### Request Example ```javascript const color = createColor(232, 67, 147, 1); // Color object methods: color.hex(); // '#e84393' color.isDark; // false color.textColor; // '#000000' `${color}`; // '#e84393' (toString() returns hex) ``` ``` -------------------------------- ### Import ESM functions for bundlers and Node.js Source: https://github.com/lokesh/color-thief/blob/master/index.html Import `getColorSync` and `getPaletteSync` for use in modern JavaScript environments that support ES Modules. ```javascript import { getColorSync, getPaletteSync } from 'colorthief'; ``` -------------------------------- ### ES Module Import Source: https://github.com/lokesh/color-thief/blob/master/index.html How to import Color Thief as an ES module for use in the browser without a bundler. ```APIDOC ## ES module in the browser (no bundler) ```html ``` ``` -------------------------------- ### Configuring getPalette Options Source: https://github.com/lokesh/color-thief/blob/master/V3.md Positional arguments for getPalette are removed. Use an options object with named properties like colorCount and quality for clarity and future compatibility. ```typescript const palette = await getPalette(img, { colorCount: 5, quality: 10 }); ``` -------------------------------- ### Import CommonJS functions for Node.js Source: https://github.com/lokesh/color-thief/blob/master/index.html Import `getColor` and `getPalette` using `require` for use in Node.js environments with CommonJS module system. ```javascript const { getColor, getPalette } = require('colorthief'); ``` -------------------------------- ### observe() - Reactive Color Observation Source: https://github.com/lokesh/color-thief/blob/master/index.html Reactively monitor DOM elements (like video, canvas, or img) and receive palette updates when they change. Includes options for throttling and handling different element types. ```APIDOC ## observe() ### Description Reactively watch a source and get palette updates whenever it changes. Works with `