Search code examples
phpcolorshexrgbbrightness

Help needed with PHP function: brightness(); making RGB colors darker/brighter


Imagine a valid #RGB color in hexadecimal, defined as $color = "#f7b9a0";

Now I want to have php derive from this $color two other colors which are slightly lighter/darker (same hue/color but just altered brightness). What ways could I achieve this? What code will generate this? I have the feeling I need something simple like:

brightness(input rgb color, ± number of steps); // function outputs the new RGB
 // ?? What php code should go here??

Ideally, I wish to have something like this in my html:

.classDefault {color:<?=$color?> }
.classLighter {color:<?=brightness($color,+10)?> } /* 10 steps brighter */
.classDarker  {color:<?=brightness($color,-25)?> } /* 25 steps darker   */

What PHP code should go in the brightness(); function? for my dream to come true?
Any suggestions and or code are both very appreciated!


updated from the answer below:

function alter_brightness($colourstr, $steps) {
  $colourstr = str_replace('#','',$colourstr);
  $rhex = substr($colourstr,0,2);
  $ghex = substr($colourstr,2,2);
  $bhex = substr($colourstr,4,2);

  $r = hexdec($rhex);
  $g = hexdec($ghex);
  $b = hexdec($bhex);

  $r = max(0,min(255,$r + $steps));
  $g = max(0,min(255,$g + $steps));  
  $b = max(0,min(255,$b + $steps));

  return '#'.dechex($r).dechex($g).dechex($b);
}

### NOW LETS DEFINE MY COLOR
$color = "#2233FF";

### DERIVED BRIGHTER COLORS
$color1 = brightness($color,25);
$color2 = brightness($color,50);
$color3 = brightness($color,75);

### DERIVED DARKER COLORS
$color4 = brightness($color,-25);
$color5 = brightness($color,-50);
$color6 = brightness($color,-75);


<!-- BRIGHTER -->
<div style=" background-color:<?=$color3?>"><?=$color3?></div>
<div style=" background-color:<?=$color2?>"><?=$color2?></div>
<div style=" background-color:<?=$color1?>"><?=$color1?></div>

<!-- DEFINED CONSTANT -->
<div style=" background-color:<?=$color?>"><?=$color?></div>

<!-- DARKER -->
<div style=" background-color:<?=$color4?>"><?=$color4?></div>
<div style=" background-color:<?=$color5?>"><?=$color5?></div>
<div style=" background-color:<?=$color6?>"><?=$color6?></div>

the brighter colors work, but the darker not. Oh well half solution is at least big part of solution so Thanks very much!


Solution

  • Something along these lines...

    function alter_brightness($colourstr, $steps) {
      $colourstr = str_replace('#','',$colourstr);
      $rhex = substr($colourstr,0,2);
      $ghex = substr($colourstr,2,2);
      $bhex = substr($colourstr,4,2);
    
      $r = hexdec($rhex);
      $g = hexdec($ghex);
      $b = hexdec($bhex);
    
      $r = max(0,min(255,$r + $steps));
      $g = max(0,min(255,$g + $steps));  
      $b = max(0,min(255,$b + $steps));
    
      return '#'.dechex($r).dechex($g).dechex($b);
    }
    

    Call like $colour = alter_brightness('#2233FF',5);