Function To Darken A Colour With PHP

18th May 2008 - 1 minute read time

The following function will reduce a hexadecimal colour string by a set value. It can take three and six digit colour values.

  1. function ColorDarken($color, $dif=20)
  2. {
  3. $color = str_replace('#','', $color);
  4. $rgb = '';
  5. if (strlen($color) != 6) {
  6. // reduce the default amount a little
  7. $dif = ($dif==20)?$dif/10:$dif;
  8. for ($x = 0; $x < 3; $x++) {
  9. $c = hexdec(substr($color,(1*$x),1)) - $dif;
  10. $c = ($c < 0) ? 0 : dechex($c);
  11. $rgb .= $c;
  12. }
  13. } else {
  14. for ($x = 0; $x < 3; $x++) {
  15. $c = hexdec(substr($color, (2*$x),2)) - $dif;
  16. $c = ($c < 0) ? 0 : dechex($c);
  17. $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
  18. }
  19. }
  20. return '#'.$rgb;
  21. }

Here are some examples of use.

  1. echo ColorDarken('#123456'); // #002042
  2. echo ColorDarken('#666'); // #444
  3. echo ColorDarken('#ffffff'); // #ebebeb
  4. echo ColorDarken('#ffffff',1); // #eeeeee

Comments

Permalink

Good ;)

I used thank you ;)

Anon (Fri, 01/06/2012 - 19:24)

Add new comment

The content of this field is kept private and will not be shown publicly.