Php – How to generate lighter/darker color with PHP

colorscsshtmlPHP

I have a hex value of some color, for example #202010.

How to generate a new color which is either lighter or darker given in percent (ie. 20% darker) in PHP?

Best Answer

Adjusting colour by percent, as in the example given by Frxstrem, is not ideal.

If your colour is black (0,0,0 in RGB), you will be multiplying by zero, which will not yield any change at all. If your colour is dark gray (for instance 2,2,2 in RGB), you will have to lighten by 50% to just move up to (3,3,3). On the other hand, if you have an RGB colour of (100,100,100), the adjustment of 50% will move you up to (150,150,150), which is a much bigger change in comparison.

A much better solution would be to adjust by step/number (0-255) instead of by percent, for instance like this (PHP code):

Edit 2014-01-06: Cleaned up the code a bit.

function adjustBrightness($hex, $steps) {
    // Steps should be between -255 and 255. Negative = darker, positive = lighter
    $steps = max(-255, min(255, $steps));

    // Normalize into a six character long hex string
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
    }

    // Split into three parts: R, G and B
    $color_parts = str_split($hex, 2);
    $return = '#';

    foreach ($color_parts as $color) {
        $color   = hexdec($color); // Convert to decimal
        $color   = max(0,min(255,$color + $steps)); // Adjust color
        $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
    }

    return $return;
}