Skip to content

Instantly share code, notes, and snippets.

@olvado
Created June 27, 2011 10:19
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save olvado/1048628 to your computer and use it in GitHub Desktop.
Save olvado/1048628 to your computer and use it in GitHub Desktop.
Get the average colour of an image in javascript using getImageData in CANVAS
function getAverageColourAsRGB (img) {
var canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
rgb = {r:102,g:102,b:102}, // Set a base colour as a fallback for non-compliant browsers
pixelInterval = 5, // Rather than inspect every single pixel in the image inspect every 5th pixel
count = 0,
i = -4,
data, length;
// return the base colour for non-compliant browsers
if (!context) { return rgb; }
// set the height and width of the canvas element to that of the image
var height = canvas.height = img.naturalHeight || img.offsetHeight || img.height,
width = canvas.width = img.naturalWidth || img.offsetWidth || img.width;
context.drawImage(img, 0, 0);
try {
data = context.getImageData(0, 0, width, height);
} catch(e) {
// catch errors - usually due to cross domain security issues
alert(e);
return rgb;
}
data = data.data;
length = data.length;
while ((i += pixelInterval * 4) < length) {
count++;
rgb.r += data[i];
rgb.g += data[i+1];
rgb.b += data[i+2];
}
// floor the average values to give correct rgb values (ie: round number values)
rgb.r = Math.floor(rgb.r/count);
rgb.g = Math.floor(rgb.g/count);
rgb.b = Math.floor(rgb.b/count);
return rgb;
}
@PoppaCherry
Copy link

How can would I use this function to display data for some-image.png?

@zekrom-vale
Copy link

zekrom-vale commented Jun 1, 2017

You could do somthing like getElementById('SomeId').innerHTML= rbg; //Did not test

Also would this work with a video element like YouTube?

@gguuss
Copy link

gguuss commented Jun 25, 2019

I did this to capture the output color:

    <input type="color" id="sentcolor" value="#00ff00"/>
    let hexColor =
        "#" + rgb.r.toString(16) + rgb.g.toString(16) + rgb.b.toString(16);
    document.getElementById('sentcolor').value = hexColor;
    return hexColor;

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