Skip to content

Palette from Image — JavaScript source

Extract the dominant colors from any image as a reusable palette — median-cut quantization with population shares, hex and rgb, copyable — runs entirely in your browser.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

/**
 * palette-from-image - dominant colors from RGBA pixels via median-cut quantization.
 *
 * Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `palette-from-image` tool.
 * Ported from src/lib/palette-extract.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: dominant-color extraction usually hides behind a
 * canvas API or an npm quantizer. This port keeps the whole algorithm -
 * alpha skip, stride down-sampling, widest-channel median splits, population
 * ranking - in one dependency-free file you can read top to bottom.
 *
 * display source - part of CosmoDev's polyglot tool pages.
 */

// A swatch is a plain { r, g, b, population } object; a pixel is [r, g, b].

/** Down-sample so large images quantize in bounded time. */
const MAX_SAMPLES = 16384;

/**
 * Extract up to `maxColors` dominant swatches from raw RGBA pixels - a flat
 * byte array with 4 bytes per pixel, exactly the layout of ImageData.data.
 * Empty or fully-transparent input yields an empty palette.
 */
export function extractPalette(rgba, maxColors = 8) {
  const total = Math.floor(rgba.length / 4);
  if (total === 0) return [];

  const pixels = [];
  const stride = Math.max(1, Math.floor(total / MAX_SAMPLES));
  for (let i = 0; i < total; i += stride) {
    const o = i * 4;
    if (rgba[o + 3] === 0) continue; // skip fully transparent pixels
    pixels.push([rgba[o], rgba[o + 1], rgba[o + 2]]);
  }
  if (pixels.length === 0) return [];

  // Median-cut: start from one bucket of everything, split until we have
  // maxColors buckets or no bucket has more than one distinct value.
  const buckets = [pixels];
  while (buckets.length < maxColors) {
    // Widest-range bucket with more than one distinct value wins the split.
    let bestIdx = -1;
    let bestRange = 1; // Range 1 (exact duplicates only) never splits further.
    for (let i = 0; i < buckets.length; i++) {
      const range = channelRange(buckets[i]);
      if (range > bestRange) {
        bestRange = range;
        bestIdx = i;
      }
    }
    if (bestIdx === -1) break; // every bucket is uniform - done
    const bucket = buckets.splice(bestIdx, 1)[0];
    buckets.push(...splitBucket(bucket));
  }

  return buckets
    .filter((bucket) => bucket.length > 0)
    .map((bucket) => ({
      r: tsRound(bucket.reduce((s, p) => s + p[0], 0), bucket.length),
      g: tsRound(bucket.reduce((s, p) => s + p[1], 0), bucket.length),
      b: tsRound(bucket.reduce((s, p) => s + p[2], 0), bucket.length),
      population: bucket.length,
    }))
    .sort((a, b) => b.population - a.population); // stable - matches the TS lib
}

/** Math.round as the spec defines it: floor(x + 0.5). Kept explicit so the
 * other language ports (banker's / away-from-zero rounding) can mirror it. */
function tsRound(sum, n) {
  return Math.floor(sum / n + 0.5);
}

/** The widest single-channel span (0-255) inside a bucket. */
function channelRange(bucket) {
  const [lo, hi] = channelExtremes(bucket);
  return Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]);
}

/** Per-channel [min, max] reduced over a bucket. */
function channelExtremes(bucket) {
  const lo = [255, 255, 255];
  const hi = [0, 0, 0];
  for (const [r, g, b] of bucket) {
    lo[0] = Math.min(lo[0], r); hi[0] = Math.max(hi[0], r);
    lo[1] = Math.min(lo[1], g); hi[1] = Math.max(hi[1], g);
    lo[2] = Math.min(lo[2], b); hi[2] = Math.max(hi[2], b);
  }
  return [lo, hi];
}

/** Split a bucket in two at the median of its widest channel. */
function splitBucket(bucket) {
  const [lo, hi] = channelExtremes(bucket);
  const ranges = [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]];
  // First max wins ties - r, then g, then b, exactly like the TS reduce.
  let channel = 0;
  for (const c of [1, 2]) {
    if (ranges[c] > ranges[channel]) channel = c;
  }

  const sorted = [...bucket].sort((a, b) => a[channel] - b[channel]); // stable
  const mid = Math.floor(sorted.length / 2);
  return [sorted.slice(0, mid), sorted.slice(mid)];
}

/** Format a swatch as #rrggbb. */
export function toHex({ r, g, b }) {
  return '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
}

// Usage:
//   const swatches = extractPalette(imageData.data, 6);
//   for (const s of swatches) console.log(toHex(s), s.population);

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →