Skip to content

Instantly share code, notes, and snippets.

@motss
Created January 27, 2026 19:32
Show Gist options
  • Select an option

  • Save motss/bf4297909165889d20b0ef0bb8468b82 to your computer and use it in GitHub Desktop.

Select an option

Save motss/bf4297909165889d20b0ef0bb8468b82 to your computer and use it in GitHub Desktop.
Analyze Top K colors from image
<h3>Analyzing center 100×100 pixels from: https://picsum.dev/800/600</h3>
<canvas id="canvas" style="border:1px solid #ccc;"></canvas>
<div id="colors"></div>
<code>Decoded takes: <time></time>ms.</code>
<script>
async function analyzeImage(url) {
const decodedElement = document.querySelector('time');
const img = new Image();
img.crossOrigin = "anonymous"; // allow cross-origin fetch
img.src = url;
img.onload = async () => {
const decodeAt = performance.now();
const cropWidth = 100;
const cropHeight = 100;
const startX = (img.width - cropWidth) / 2;
const startY = (img.height - cropHeight) / 2;
// Create cropped ImageBitmap
const bitmap = await createImageBitmap(img, startX, startY, cropWidth, cropHeight);
// Draw onto canvas
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = cropWidth;
canvas.height = cropHeight;
ctx.drawImage(bitmap, 0, 0);
// Get pixel data
const imageData = ctx.getImageData(0, 0, cropWidth, cropHeight);
const data = imageData.data;
// Count colors
const colorCount = {};
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}`;
colorCount[key] = (colorCount[key] || 0) + 1;
}
// Sort by frequency
const topColors = Object.entries(colorCount)
.sort((a, b) => b[1] - a[1])
.slice(0, 10);
const decodedAt = performance.now() - decodeAt;
console.log('Decoded takes: %dms', decodedAt);
// Show results
const colorsDiv = document.getElementById('colors');
colorsDiv.innerHTML = "<h4>Top 10 Colors:</h4>";
topColors.forEach(([rgb, count], idx) => {
const colorBox = document.createElement("div");
colorBox.style.display = "inline-block";
colorBox.style.width = "50px";
colorBox.style.height = "50px";
colorBox.style.margin = "5px";
colorBox.style.backgroundColor = `rgb(${rgb})`;
colorBox.title = `#${idx+1}: rgb(${rgb}) — ${count} pixels`;
colorsDiv.appendChild(colorBox);
});
decodedElement.textContent = decodedAt;
console.log("Top 10 colors:", topColors.map(([rgb, count]) => ({
rgb: `rgb(${rgb})`,
count
})));
};
}
// Run analysis on your provided image URL
analyzeImage("https://picsum.photos/3840/2160");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment