`
}).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 `