{"name":"colorthief","version":"3.3.0","keywords":["color","palette","sampling","image","picture","photo","canvas","oklch","swatch"],"author":{"url":"http://lokeshdhakar.com/","name":"Lokesh Dhakar","email":"lokesh.dhakar@gmail.com"},"license":"MIT","_id":"colorthief@3.3.0","maintainers":[{"name":"lokesh.dhakar","email":"lokesh.dhakar@gmail.com"}],"homepage":"http://lokeshdhakar.com/projects/color-thief/","bugs":{"url":"https://github.com/lokesh/color-thief/issues"},"bin":{"colorthief":"dist/cli.js"},"dist":{"shasum":"175394e63080afc1390014dd7914bbe8f300aa05","tarball":"http://registry-npm.ywwl.com/colorthief/download/colorthief-3.3.0.tgz","fileCount":56,"integrity":"sha512-0hMB8YKZjI5QqLjw2FwN2EQOA8A8GW32TNWUJMdxh+dL3fi6WM1Q1iJK25R4X9d2L6EhV+7ey25CQHTTvMik4Q==","signatures":[{"sig":"MEQCIGAUqIlMarlNvcFPLQPnowK33NzAa7s3/UO7dURtATSzAiBRi4HZifT2cQ0kB6R7inx7CiIDf9CFHnZ8rtLhOrxwLA==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1483262,"size":330539,"noattachment":false,"key":"/colorthief/-/colorthief-3.3.0.tgz"},"main":"./dist/index.cjs","type":"module","types":"./dist/types/index.d.ts","module":"./dist/index.js","exports":{".":{"import":{"types":"./dist/types/index.d.ts","default":"./dist/index.js"},"browser":{"import":{"types":"./dist/types/index.d.ts","default":"./dist/index.browser.js"},"require":{"types":"./dist/types/index.d.cts","default":"./dist/index.browser.cjs"}},"require":{"types":"./dist/types/index.d.cts","default":"./dist/index.cjs"}},"./internals":{"import":{"types":"./dist/types/internals.d.ts","default":"./dist/internals.js"},"browser":{"import":{"types":"./dist/types/internals.browser.d.ts","default":"./dist/internals.browser.js"},"require":{"types":"./dist/types/internals.browser.d.cts","default":"./dist/internals.browser.cjs"}},"require":{"types":"./dist/types/internals.d.cts","default":"./dist/internals.cjs"}}},"gitHead":"e1ceaa316d67f9e25f497c0e803ac2672d9d4ee5","scripts":{"dev":"http-server","test":"mocha && cypress run --config video=false","build":"tsup","watch":"tsup --watch","cypress":"cypress open","test:node":"mocha","typecheck":"tsc --noEmit","test:browser":"cypress run --headed --browser chrome","prepublishOnly":"npm run build"},"_npmUser":{"name":"lokesh.dhakar","email":"lokesh.dhakar@gmail.com"},"repository":{"url":"git+https://github.com/lokesh/color-thief.git","type":"git"},"_npmVersion":"11.8.0","description":"Extract dominant colors and palettes from images — TypeScript, OKLCH, semantic swatches, live video extraction.","directories":{},"_nodeVersion":"24.13.1","_hasShrinkwrap":false,"devDependencies":{"chai":"^4.2.0","tsup":"^8.0.0","mocha":"^10.2.0","sharp":"^0.34.5","cypress":"^13.15.0","mustache":"^3.0.1","typescript":"^5.3.0","@types/node":"^20.11.0","http-server":"^14.1.1","chai-as-promised":"^7.1.1"},"peerDependencies":{"sharp":">=0.33.0"},"peerDependenciesMeta":{"sharp":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/colorthief_3.3.0_1772652359276_0.0834242955621094","host":"s3://npm-registry-packages-npm-production"},"readme":"# Color Thief\n\n> Extract dominant colors and palettes from images in the browser and Node.js.\n\n[![npm version](https://img.shields.io/npm/v/colorthief)](https://www.npmjs.com/package/colorthief)\n[![npm bundle size](https://img.shields.io/bundlephobia/minzip/colorthief)](https://bundlephobia.com/package/colorthief)\n[![types](https://img.shields.io/npm/types/colorthief)](https://www.npmjs.com/package/colorthief)\n\n## Install\n\n```bash\nnpm install colorthief\n```\n\nOr load directly from a CDN:\n\n```html\n<script src=\"https://unpkg.com/colorthief@3/dist/umd/color-thief.global.js\"></script>\n```\n\n## Quick Start\n\n```js\nimport { getColorSync, getPaletteSync, getSwatches } from 'colorthief';\n\n// Dominant color\nconst color = getColorSync(img);\ncolor.hex();      // '#e84393'\ncolor.css();      // 'rgb(232, 67, 147)'\ncolor.isDark;     // false\ncolor.textColor;  // '#000000'\n\n// Palette\nconst palette = getPaletteSync(img, { colorCount: 6 });\npalette.forEach(c => console.log(c.hex()));\n\n// Semantic swatches (Vibrant, Muted, DarkVibrant, etc.)\nconst swatches = await getSwatches(img);\nswatches.Vibrant?.color.hex();\n```\n\n## Features\n\n- **TypeScript** — full type definitions included\n- **Browser + Node.js** — same API, both platforms\n- **Sync & async** — synchronous browser API, async for Node.js\n- **Live extraction** — `observe()` watches video, canvas, or img elements and emits palette updates reactively\n- **Worker friendly** — runs inside your own Web Worker via `ImageBitmap` or `OffscreenCanvas`\n- **Progressive extraction** — 3-pass refinement for instant rough results\n- **OKLCH quantization** — perceptually uniform palettes via `colorSpace: 'oklch'`\n- **Semantic swatches** — Vibrant, Muted, DarkVibrant, DarkMuted, LightVibrant, LightMuted\n- **Rich Color objects** — `.hex()`, `.rgb()`, `.hsl()`, `.oklch()`, `.css()`, contrast ratios, text color recommendations\n- **WCAG contrast** — `color.contrast.white`, `color.contrast.black`, `color.contrast.foreground`\n- **AbortSignal** — cancel in-flight extractions\n- **CLI** — `colorthief photo.jpg` with JSON, CSS, and ANSI output\n- **Zero runtime dependencies**\n\n## API at a Glance\n\n| Function | Description |\n|---|---|\n| `getColorSync(source, options?)` | Dominant color (sync, browser only) |\n| `getPaletteSync(source, options?)` | Color palette (sync, browser only) |\n| `getSwatchesSync(source, options?)` | Semantic swatches (sync, browser only) |\n| `getColor(source, options?)` | Dominant color (async, browser + Node.js) |\n| `getPalette(source, options?)` | Color palette (async, browser + Node.js) |\n| `getSwatches(source, options?)` | Semantic swatches (async, browser + Node.js) |\n| `getPaletteProgressive(source, options?)` | 3-pass progressive palette (async generator) |\n| `observe(source, options)` | Watch a source and emit palette updates (browser only) |\n| `createColor(r, g, b, population)` | Build a Color object from RGB values |\n\n### Options\n\n| Option | Default | Description |\n|---|---|---|\n| `colorCount` | `10` | Number of palette colors (2–20) |\n| `quality` | `10` | Sampling rate (1 = every pixel, 10 = every 10th) |\n| `colorSpace` | `'oklch'` | Quantization space: `'rgb'` or `'oklch'` |\n| `region` | — | Sample a sub-rectangle: `{ x, y, width, height }` as 0–1 fractions |\n| `gamut` | `'srgb'` | Output gamut: `'srgb'`, `'display-p3'`, or `'auto'` (browser only) |\n| `worker` | `false` | **Deprecated** — ignored as of v3, removed in v4. See [Web Workers](#web-workers) |\n| `signal` | — | `AbortSignal` to cancel extraction |\n| `ignoreWhite` | `true` | Skip white pixels |\n\n### Color Object\n\n| Property / Method | Returns |\n|---|---|\n| `.rgb()` | `{ r, g, b }` |\n| `.hex()` | `'#ff8000'` |\n| `.hsl()` | `{ h, s, l }` |\n| `.oklch()` | `{ l, c, h }` |\n| `.css(format?)` | `'rgb(255, 128, 0)'`, `'hsl(…)'`, or `'oklch(…)'` — a P3 color's default `.css()` is `color(display-p3 …)` |\n| `.array()` | `[r, g, b]` |\n| `.gamut` | `'srgb'` or `'display-p3'` |\n| `.toString()` | Hex string (works in template literals) |\n| `.textColor` | `'#ffffff'` or `'#000000'` |\n| `.isDark` / `.isLight` | Boolean |\n| `.contrast` | `{ white, black, foreground }` — WCAG ratios |\n| `.population` | Raw pixel count |\n| `.proportion` | 0–1 share of total |\n\n## Region extraction\n\nPass a `region` to sample only part of the image. Coordinates are fractions of\nthe image size (0–1) measured from the top-left, so a region is\nresolution-independent — the same values work for a thumbnail and the full-size\noriginal.\n\n```js\n// Colors from the bottom third — e.g. for a gradient that overlaps the\n// bottom of the image\nconst palette = await getPalette(img, {\n    region: { x: 0, y: 0.66, width: 1, height: 0.34 },\n});\n\n// Center crop\nconst color = await getColor(img, {\n    region: { x: 0.25, y: 0.25, width: 0.5, height: 0.5 },\n});\n```\n\nWorks everywhere an option object does: `getColor`, `getPalette`, `getSwatches`,\n`getPaletteProgressive`, the `*Sync` functions, `observe()`, and the CLI — in\nboth browser and Node. A region that runs past the right or bottom edge is\nclamped to the image; out-of-range or zero-sized values throw.\n\n## Browser\n\n```js\nimport { getColorSync, getPaletteSync } from 'colorthief';\n\nconst img = document.querySelector('img');\nconst color = getColorSync(img);\nconsole.log(color.hex());\n\nconst palette = getPaletteSync(img, { colorCount: 5 });\n```\n\nAccepts `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, `ImageData`, `ImageBitmap`, and `OffscreenCanvas`.\n\n### Wide-gamut (Display P3)\n\nBy default colors are read and reported in sRGB. For P3-tagged / wide-gamut images, pass `gamut` to preserve the extra saturation:\n\n```js\n// Force P3: read the image through a P3 canvas, report P3 colors\nconst palette = await getPalette(img, { gamut: 'display-p3' });\npalette[0].css();            // 'color(display-p3 0.92 0.2 0.14)'\npalette[0].gamut;            // 'display-p3'\n\n// Auto: report P3 only when the image actually uses out-of-sRGB colors,\n// otherwise behave exactly like sRGB\nconst auto = await getPalette(img, { gamut: 'auto' });\n```\n\n`.rgb()`, `.array()`, and `.hex()` always return **sRGB** (gamut-mapped when the color is P3), so existing `rgb(...)` strings keep working. The wide-gamut values live in `.css()` and `.oklch()`; use `.rgb('display-p3')` for the raw P3 components. Falls back to sRGB where P3 canvas support is unavailable. Node output is sRGB for now.\n\n### Live extraction with observe()\n\n```js\nimport { observe } from 'colorthief';\n\n// Watch a video and update ambient lighting as it plays\nconst controller = observe(videoElement, {\n    throttle: 200,    // ms between updates\n    colorCount: 5,\n    onChange(palette) {\n        updateAmbientBackground(palette);\n    },\n});\n\n// Stop when done\ncontroller.stop();\n```\n\nWorks with `<video>`, `<canvas>`, and `<img>` elements. For images, it uses a MutationObserver to detect `src` changes. For video and canvas, it polls using requestAnimationFrame with throttle.\n\n### Web Workers\n\nTo keep extraction off the main thread, run Color Thief *inside* your own worker and hand it an `ImageBitmap`. Bitmaps are transferable, so the pixels move without being copied, and decoding, sampling, and quantization all happen off-thread.\n\n```js\n// main.js\nconst bitmap = await createImageBitmap(await (await fetch(url)).blob());\nconst worker = new Worker('./palette-worker.js', { type: 'module' });\nworker.postMessage({ bitmap }, [bitmap]); // transferred, not cloned\nworker.onmessage = (e) => render(e.data.palette);\n```\n\n```js\n// palette-worker.js\nimport { getPalette } from 'colorthief';\n\nself.onmessage = async ({ data }) => {\n    const palette = await getPalette(data.bitmap, { colorCount: 5 });\n    // Color objects don't survive structured clone — send plain data\n    self.postMessage({ palette: palette.map((c) => c.hex()) });\n};\n```\n\n> **Deprecated:** the `worker: true` option is ignored as of v3 and will be removed in v4, along with the `isWorkerSupported`, `extractInWorker`, and `terminateWorker` exports from `colorthief/internals`. It only moved quantization off-thread while leaving decoding, pixel sampling, and the structured clone of the pixel array on the main thread — and serializing that array cost several times more than the quantization it saved. It also quantized in RGB while the default path uses OKLCH, so `worker: true` returned different colors. Calls that pass it now go through the normal pipeline and log a one-time warning.\n\n## Node.js\n\n```js\nimport { getColor, getPalette } from 'colorthief';\n\nconst color = await getColor('/path/to/image.jpg');\nconsole.log(color.hex());\n\nconst palette = await getPalette(Buffer.from(data), { colorCount: 5 });\n```\n\nAccepts file paths and Buffers. Uses [sharp](https://sharp.pixelplumbing.com/) for image decoding.\n\n## CLI\n\n### Quick start\n\n```bash\nnpx colorthief-cli photo.jpg\n```\n\nThe `colorthief-cli` package bundles everything needed (including sharp for image\ndecoding), so it works immediately with no extra setup.\n\n### Commands\n\n```bash\n# Dominant color\ncolorthief-cli photo.jpg\n\n# Color palette\ncolorthief-cli palette photo.jpg\n\n# Semantic swatches\ncolorthief-cli swatches photo.jpg\n```\n\n### Output formats\n\n```bash\n# Default: ANSI color swatches\ncolorthief-cli photo.jpg\n# ▇▇ #e84393\n\n# JSON with full color data\ncolorthief-cli photo.jpg --json\n\n# CSS custom properties\ncolorthief-cli palette photo.jpg --css\n# :root {\n#     --color-1: #e84393;\n#     --color-2: #6c5ce7;\n# }\n```\n\n### Options\n\n```bash\ncolorthief-cli palette photo.jpg --count 5        # Number of colors (2-20)\ncolorthief-cli photo.jpg --quality 1              # Sampling quality (1=best)\ncolorthief-cli photo.jpg --color-space rgb        # Color space (rgb or oklch)\ncolorthief-cli photo.jpg --region 0,0.66,1,0.34   # Sample the bottom third\n```\n\n`--region` takes `x,y,width,height` as fractions of the image size (0–1), the\nsame as the `region` option.\n\nStdin is supported — use `-` or pipe directly:\n\n```bash\ncat photo.jpg | colorthief-cli -\n```\n\nMultiple files are supported. Output is prefixed with filenames, and `--json` wraps\nresults in an object keyed by filename.\n\n> **Note:** If you already have `colorthief` and `sharp` installed in a project, you\n> can also use `colorthief` directly as the command name (without the `-cli` suffix).\n\n## Links\n\n- [Demo page & live examples](https://lokeshdhakar.com/projects/color-thief/)\n- [GitHub](https://github.com/lokesh/color-thief)\n- [npm](https://www.npmjs.com/package/colorthief)\n\n## Contributing\n\n```bash\nnpm run build          # Build all dist formats\nnpm run test           # Run all tests (Mocha + Cypress)\nnpm run test:node      # Node tests only\nnpm run test:browser   # Browser tests (requires npm run dev)\nnpm run dev            # Start local server on port 8080\n```\n\n## Releasing\n\n```bash\n# 1. Make sure you're on master with a clean working tree\ngit status\n\n# 2. Run the full test suite\nnpm run build\nnpm run test:node\nnpm run test:browser   # requires npm run dev in another terminal\n\n# 3. Preview what will be published\nnpm pack --dry-run\n\n# 4. Tag and publish\nnpm version <major|minor|patch>   # bumps version, creates git tag\nnpm publish                       # builds via prepublishOnly, then publishes\ngit push && git push --tags\n```\n\n## License\n\n[MIT](LICENSE) - Lokesh Dhakar\n","publish_time":1772652359535,"_cnpm_publish_time":1772652359535,"dist-tags":{"latest":"3.5.0"}}