How to Extract Color Palettes from Any Image Using JavaScript (Step-by-Step Guide) π¨
Choosing the right color palette is a common challenge for developers and designers.
Instead of manually guessing colors, you can extract them directly from any image using JavaScript.
In this guide, weβll build a simple tool that does exactly that.
π What Weβre Building
Upload an image
Extract dominant colors
Display a clean color palette
π¦ Step 1: HTML Structure
<input type="file" id="imageInput" accept="image/*" />
<canvas id="canvas" style="display:none;"></canvas>
<div id="palette"></div>
βοΈ Step 2: Load Image into Canvas
const input = document.getElementById("imageInput");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
input.addEventListener("change", function () {
const file = this.files[0];
const img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const colors = extractColors(imageData.data);
displayColors(colors);
};
img.src = URL.createObjectURL(file);
});
π¨ Step 3: Extract Dominant Colors
function extractColors(data) {
const colorMap = {};
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const key = `\({r},\){g},${b}`;
colorMap[key] = (colorMap[key] || 0) + 1;
}
return Object.entries(colorMap)
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
.map(([rgb]) => `rgb(${rgb})`);
}
πΌ Step 4: Display the Palette
function displayColors(colors) {
const palette = document.getElementById("palette");
palette.innerHTML = "";
colors.forEach(color => {
const div = document.createElement("div");
div.style.background = color;
div.style.width = "80px";
div.style.height = "80px";
div.style.display = "inline-block";
div.style.margin = "5px";
palette.appendChild(div);
});
}
β‘ How It Works
The image is drawn onto a hidden canvas
Pixel data is extracted
Colors are grouped and counted
Top colors are selected as dominant palette
π₯ Improve This Further
You can enhance this tool by:
Converting RGB to HEX
Using K-Means clustering for better accuracy
Reducing image size for performance
π§ͺ Try a Live Version
If you donβt want to build this from scratch, you can try a ready-made version here:
π― Conclusion
Extracting colors from images using JavaScript is simple and powerful.
This technique can be used in:
UI/UX tools
Design systems
Branding workflows
π¬ Final Thoughts
If you found this useful, let me know: π What feature would you add next?
Happy coding π

