Skip to content

Instantly share code, notes, and snippets.

@bsh314
Created May 9, 2018 06:33
Show Gist options
  • Save bsh314/9e2f87dc3555281b0a1f8ebc016386e9 to your computer and use it in GitHub Desktop.
Save bsh314/9e2f87dc3555281b0a1f8ebc016386e9 to your computer and use it in GitHub Desktop.
image main color finder
private getAverageRGB(imgEl) {
const blockSize = 5; // only visit every 5 pixels
const defaultRGB = { r: 0, g: 0, b: 0 }; // for non-supporting envs
const canvas = document.createElement('canvas');
const context = canvas.getContext && canvas.getContext('2d');
const rgb = { r: 0, g: 0, b: 0 };
let data, width, height;
let i = -4;
let length;
let count = 0;
if (!context) {
return defaultRGB;
}
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
context.drawImage(imgEl, 0, 0);
try {
data = context.getImageData(0, 0, width, height);
} catch (e) {
/* security error, img on diff domain */
return defaultRGB;
}
length = data.data.length;
while ((i += blockSize * 4) < length) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i + 1];
rgb.b += data.data[i + 2];
}
// tslint:disable:no-bitwise
rgb.r = ~~(rgb.r / count);
rgb.g = ~~(rgb.g / count);
rgb.b = ~~(rgb.b / count);
return rgb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment