20100124

How to get a contrasting font color for a given background ?

This is a sample code to give a font color with a good contrast for a given background color.

That php code snipped could be useful in case you give your users the option to set a custom background but not the font color (to avoid too many options) and you want that your text are always visible.

It simply returns a font color white or black depending on the background, but you can modify the function get_contrast if you want something more sophisticated.

The main function is:


function get_font_color($color)
{
$ar=html2rgb($color);
return get_contrast($ar[0], $ar[1], $ar[2]);
}


Supporting functions:

function get_contrast ($r, $g, $b)
{// returns white or black depending on the background
// in red green and blue
$a = 1 - ( 0.299*$r + 0.587*$g + 0.114*$b)/255;
if ($a<0.5)
{
return '#000';
}
else
{
return '#fff';
}
}

function html2rgb($color)
{// gets an array of R,G,B from an hexadecimal
// color in html format
if ($color[0] == '#') $color = substr($color, 1);

if (strlen($color) == 6)
{
list($r, $g, $b) = array($color[0].$color[1],
$color[2].$color[3],
$color[4].$color[5]);
}
elseif (strlen($color) == 3)
{
list($r, $g, $b) = array($color[0].$color[0],
$color[1].$color[1],
$color[2].$color[2]);
}
else
{
return false;
}
$r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

return array($r, $g, $b);
}


Unit testing:

$i=0;
while ($i<1600000)
{
$rgb='#'.strtoupper(str_pad(dechex($i), 6, '0', STR_PAD_LEFT));
echo '<div style="background-color:'.$rgb.'; color:'.get_font_color($rgb).'">'.$rgb.'</div>';
$i++;
}


Thanks to this web entries:
Determine font color based on background color
Convert RGB from an HTML Hex Color

1 comentario:

Anónimo dijo...

It work thanks very much