Color Palette from Image: how it works and how to build one
Pull the main colors out of any photo or logo. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Find the dominant colors of a photo, logo or screenshot, with how much of the image each one covers. Copy HEX values or the whole palette as CSS variables for your theme.
When to use it
- Brand colors from a logo or photo
- Matching a website to a hero image
- Design inspiration
How to use it
- Choose or drop an image.
- Set how many colors you want.
- Copy the HEX codes or CSS variables.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/color-palette-extractor
How it works
Finding the main colors of a photo is a clustering problem. The tool shrinks the image to about 100 pixels wide (enough to keep the colors, much faster), reads every pixel with getImageData, and runs k-means: start with k random colors, assign every pixel to the nearest one, move each color to the average of its pixels, and repeat.
The clusters with the most pixels become the palette.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
palette.ts (ts)
export function palette(px: number[][], k = 6, rounds = 10) {
let centers = Array.from({ length: k }, () => px[Math.floor(Math.random() * px.length)]);
let groups: number[][][] = [];
for (let r = 0; r < rounds; r++) {
groups = centers.map(() => []);
for (const p of px) {
let best = 0, bestD = Infinity;
centers.forEach((c, i) => { const d = (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2 + (p[2] - c[2]) ** 2; if (d < bestD) { bestD = d; best = i; } });
groups[best].push(p);
}
centers = groups.map((g, i) => (g.length ? [0, 1, 2].map((j) => g.reduce((s, p) => s + p[j], 0) / g.length) : centers[i]));
}
return centers.map((c, i) => ({ rgb: c.map(Math.round), share: groups[i].length / px.length })).sort((a, b) => b.share - a.share);
}
Make it production-ready
- Start with k-means++ for steadier results.
- Export as CSS variables or a Tailwind config.
Questions
How are the colors chosen?
The image is shrunk and its pixels are grouped with k-means clustering; each group’s average is one palette color.
Free, runs in your browser, nothing is uploaded.