|Detecting if a color is dark of light|
To place black or white text on it
I've got a background color in my database and I have to detect if it is dark or light. Actually, it's because Google is also always showing 'Ads by Google' in black or white.
So, does anyone know how I can check this.
You need to know how the hexadecimal system works :)
Thank you very much in advance.
This page explains how you can use hexdec to convert from hex to decimal. There is also an example in the comments of how to use it for a color, returning an array with the red, green, blue elements.
Each element will be between 0 and 255 of course. The tricky part will be deciding what 'dark' is, since a color like blue for example even at 255 would alway look good with white text, but a 255 green might look better with white, then you have combinations etc..
Now if you are dealing with just shades of gray it would be easier. I would split it around 150 for the white/black text decision.
From this W3C document [w3.org]:
Color brightness is determined by the following formula:
((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
Also search for "Colour Contrast Check" for a fascinating online colour contrast too.
I've made something simple.
Nice find there Longhaired Genius!
Maybe try this something like this:
// returns brightness value from 0 to 255
// strip off any leading #
$hex = str_replace('#', '', $hex);
$c_r = hexdec(substr($hex, 0, 2));
$c_g = hexdec(substr($hex, 2, 2));
$c_b = hexdec(substr($hex, 4, 2));
return (($c_r * 299) + ($c_g * 587) + ($c_b * 114)) / 1000;
$color = "#******";
if ($get_brightness($color) > 130) // will have to experiment with this number
echo '<font style="color:black;">Black</font>';
echo '<font style="color:white;">White</font>';
My way is also working, but your's is better.
Is there also a way you can check if there's enough contrast between two colors? So you can check if there's a light yellow color on a light blue background for example.
From the same W3C document:
Color difference is determined by the following formula:
(maximum (Red value 1, Red value 2) - minimum (Red value 1, Red value 2)) + (maximum (Green value 1, Green value 2) - minimum (Green value 1, Green value 2)) + (maximum (Blue value 1, Blue value 2) - minimum (Blue value 1, Blue value 2))
The rage for color brightness difference is 125. The range for color difference is 500.