Wednesday, June 25, 2008

HEX to RGB to greyscale conversion

Converting a hex value to the equivalent grey scale is not as simple as averaging the values and dividing by 3 as the eye responds more to the green content than to red or blue.

There are different formulas in use, but a common one is 0.30*r + 0.59*g + 0.11*b

// split HEX into RGB components
var r = hex >> 16;
var g = hex >> 8 & 0xFF;
var b = hex & 0xFF;
// create a new grey value
var grey = 0.30*r + 0.59*g + 0.11*b;
// create a new HEX colour
var k = grey.toString(16) + grey.toString(16) + grey.toString(16);

No comments: