Skip to content

Instantly share code, notes, and snippets.

@neonxp
Last active February 27, 2017 09:05
Show Gist options
  • Save neonxp/784df91cf60ccf6985a1cdfef6c35a27 to your computer and use it in GitHub Desktop.
Save neonxp/784df91cf60ccf6985a1cdfef6c35a27 to your computer and use it in GitHub Desktop.
Определение доминирующего цвета в иконке
function magic(image) {
var imgWidth = 18;
var imgHeight = 18;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// Draw white Rect to avoid problems with favicon opacity
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(0, 0, imgWidth, imgHeight);
ctx.drawImage(image, 0, 0, imgWidth, imgHeight);
try {
var data = ctx.getImageData(0, 0, imgWidth, imgHeight);
}
catch(e) {
// security error, img on diff domain
console.log("Cross-domain error");
return;
}
return avgYUV( data );
}
function sigma( x ) {
return x / (Math.abs(x) + 0.4);
}
function avgYUV( data ) {
var rgb = { r : 0, g : 0, b : 0 };
var yuv = { y : 0, u : 0, v : 0 };
var count = 0;
for ( i = 0; i<data.data.length; i=i+4 ) {
// Ignore white color. Suppose we hate it.
if ( data.data[i] == 255 &&
data.data[i + 1] == 255 &&
data.data[i + 2] == 255 ) {
continue;
}
rgb.r = data.data[i] / 255;
rgb.g = data.data[i + 1] / 255;
rgb.b = data.data[i + 2] / 255;
yuv.y += 0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b;
yuv.u += -0.147 * rgb.r - 0.289 * rgb.g + 0.436 * rgb.b;
yuv.v += 0.615 * rgb.r - 0.515 * rgb.g - 0.100 * rgb.b;
count += 1;
}
yuv.y = yuv.y/count;
yuv.u = yuv.u/count;
yuv.v = yuv.v/count;
yuv.y = sigma(yuv.y);
yuv.u = sigma(yuv.u);
yuv.v = sigma(yuv.v);
rgb.r = yuv.y + 1.3983 * yuv.v;
rgb.g = yuv.y - 0.3946 * yuv.u - 0.58060 * yuv.v;
rgb.b = yuv.y + 2.0321 * yuv.u;
rgb.r = ~~(rgb.r * 255);
rgb.g = ~~(rgb.g * 255);
rgb.b = ~~(rgb.b * 255);
return rgb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment