views:

247

answers:

3

I want users on my website to be able to pick a hex colour, and I just want to display white text for dark colours and black text for light colours. Can you work out the brightness from a hex code (preferably PHP)?

+2  A: 

You need to convert the RGB values to HLS/HSL (Hue Lightness and Saturation) you can then use the Lightness to determine whether you need light text or dark text.

This page has some details on how to the conversion in PHP as well as selecting complementary colour from this.

I've only just spotted that the site is an astrology site - so apologies if anyone's offended.

ChrisF
About astrology site: yes, that's **horrendous!** (No, just kidding, interesting they have such a programming related topic on their site, I wouldn't expect that.)
Marcel Korpel
@Marcel - I think it's to show the code behind their charts.
ChrisF
+1  A: 

If you have imagemagick extension activated, you can simply create an ImagickPixel object, call setColor with your hex value, and then call getHSL() (and get the last item of the obtained array I suppose)...

greg0ire
+3  A: 
$hex = "78ff2f"; //Bg color in hex, without any prefixing #!

//break up the color in its RGB components
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));

//do simple weighted avarage
//
//(This might be overly simplistic as different colors are perceived
// differently. That is a green of 128 might be brighter than a red of 128.
// But as long as it's just about picking a white or black text color...)
if($r + $g + $b > 382){
    //bright color, use dark font
}else{
    //dark color, use bright font
}
0scar
Works perfect, didn't even need to go into Hue and Saturation! :)
Juddling