Skip to content

Instantly share code, notes, and snippets.

@gavinsharp
Forked from leibovic/dominant-color.js
Created June 9, 2011 17:06
Show Gist options
  • Save gavinsharp/1017189 to your computer and use it in GitHub Desktop.
Save gavinsharp/1017189 to your computer and use it in GitHub Desktop.
Dominant Color
function getDominantColor(aImg) {
let canvas = document.createElement("canvas");
canvas.height = aImg.height;
canvas.width = aImg.width;
let context = canvas.getContext("2d");
context.drawImage(aImg, 0, 0);
// keep track of how many times a color appears in the image
let colorCount = {};
let maxCount = 0;
let dominantColor = 0xFFFFFF;
// data is an array of a series of 4 one-byte values representing the rgba values of each pixel
let data = context.getImageData(0, 0, aImg.height, aImg.width).data;
for (let i = 0; i < data.length; i += 4) {
// ignore transparent pixels
if (data[i+3] == 0)
continue;
let color = (data[i] << 16) | (data[i+1] << 8) | data[i+2];
if (color == 0xFFFFFF)
continue;
colorCount[color] = (colorCount[color] || 0)+1;
// keep track of the color that appears the most times
if (colorCount[color] > maxCount) {
maxCount = colorCount[color];
dominantColor = color;
}
}
return dominantColor.toString(16);
}
@gavinsharp
Copy link
Author

(untested, for the moment!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment