18th May 2008 - 2 minutes read time
The following function will reduce a hexadecimal colour string by a set value. It can take three and six digit colour values.
function ColorDarken($color, $dif=20)
{
$color = str_replace('#','', $color);
$rgb = '';
if (strlen($color) != 6) {
// reduce the default amount a little
$dif = ($dif==20)?$dif/10:$dif;
for ($x = 0; $x < 3; $x++) {
$c = hexdec(substr($color,(1*$x),1)) - $dif;
$c = ($c < 0) ? 0 : dechex($c);
$rgb .= $c;
}
} else {
for ($x = 0; $x < 3; $x++) {
$c = hexdec(substr($color, (2*$x),2)) - $dif;
$c = ($c < 0) ? 0 : dechex($c);
$rgb .= (strlen($c) < 2) ? '0'.$c : $c;
}
}
return '#'.$rgb;
}
Here are some examples of use.
echo ColorDarken('#123456'); // #002042
echo ColorDarken('#666'); // #444
echo ColorDarken('#ffffff'); // #ebebeb
echo ColorDarken('#ffffff',1); // #eeeeee