Skip to content

Instantly share code, notes, and snippets.

@dctalbot
Created June 26, 2019 20:26
Show Gist options
  • Save dctalbot/40e3ef209e12f50800734d005131d820 to your computer and use it in GitHub Desktop.
Save dctalbot/40e3ef209e12f50800734d005131d820 to your computer and use it in GitHub Desktop.
Get Common or "Dominant" Color from Image
drawImage = async img_path => {
let canvas = document.createElement("canvas");
canvas.src = img_path;
const context = canvas.getContext("2d");
const img = await loadImage(img_path);
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
return { canvas, context };
};
function loadImage(img_path) {
return new Promise(r => {
let i = new Image();
i.onload = () => r(i);
i.src = img_path;
});
}
calculateResult = (canvas, context) => {
let store = {};
const imgData = context.getImageData(0, 0, canvas.width, canvas.height);
const data = imgData.data;
const total_pixels = canvas.width * canvas.height;
const coverage = total_pixels / 4;
const max_pixel_index = total_pixels - 1;
for (let i = 0; i < coverage; ++i) {
const x = getPixelIndex(Math.floor(Math.random() * max_pixel_index));
const key = `${data[x]},${data[x + 1]},${data[x + 2]}`;
const val = store[key];
store[key] = val ? val + 1 : 1;
}
const rgb_code = Object.keys(store).reduce((a, b) =>
store[a] > store[b] ? a : b
);
return `rgb(${rgb_code})`;
};
function getPixelIndex(numToRound) {
//Each pixel is 4 units long: r,g,b,a
const remainder = numToRound % 4;
if (remainder == 0) return numToRound;
return numToRound + 4 - remainder;
}
main = async () => {
const { canvas, context } = await drawImage("./img/wallpaper.jpg");
const result = await calculateResult(canvas, context);
console.log(result);
};
main();
@dctalbot
Copy link
Author

dctalbot commented Jun 26, 2019

Just replace "./img/wallpaper.jpg" with the file path to your image and run in the browser (may have to use firefox because Chrome can CORS block your own machine)

@TheoElia
Copy link

Thanks...this is great

@emmsdan
Copy link

emmsdan commented Jan 31, 2020

Nice one @dctalbot
Thank you.
I think I would use this for my next project

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