17th
JUN

Darken or lighten colours dynamically using PHP

Posted by Lee under Programming

For a recent client’s site we needed to have a function that would be able to darken a given hex colour (eg. #f4129c) on the fly (it was changing the border colour to be darker then the background colour). It took a while to find anything that could remotely do this as many samples seemed to have flaws with certain colours. We also decided to make our own function able to make a colour lighter as well as darker.

Below is the function that we developed for this – we got a few ideas for the function from the CSS Colors Class developed by BarelyFitz Designs and we highly recommend this class if you are needing more advanced colour functions such as colour comparing.

Below is a snippet of the code and usuage guide.

PHP Function

function colourBrightness($hex, $percent) {
	// Work out if hash given
	$hash = '';
	if (stristr($hex,'#')) {
		$hex = str_replace('#','',$hex);
		$hash = '#';
	}
	/// HEX TO RGB
	$rgb = array(hexdec(substr($hex,0,2)), hexdec(substr($hex,2,2)), hexdec(substr($hex,4,2)));
	//// CALCULATE 
	for ($i=0; $i<3; $i++) {
		// See if brighter or darker
		if ($percent > 0) {
			// Lighter
			$rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1-$percent));
		} else {
			// Darker
			$positivePercent = $percent - ($percent*2);
			$rgb[$i] = round($rgb[$i] * $positivePercent) + round(0 * (1-$positivePercent));
		}
		// In case rounding up causes us to go to 256
		if ($rgb[$i] > 255) {
			$rgb[$i] = 255;
		}
	}
	//// RBG to Hex
	$hex = '';
	for($i=0; $i < 3; $i++) {
		// Convert the decimal digit to hex
		$hexDigit = dechex($rgb[$i]);
		// Add a leading zero if necessary
		if(strlen($hexDigit) == 1) {
		$hexDigit = "0" . $hexDigit;
		}
		// Append to the hex string
		$hex .= $hexDigit;
	}
	return $hash.$hex;
}

Function Usuage

You do not have to give the colour with the ‘#’ in fron but if you do it will still return the new hex colour with the ‘#’ auto-magically.

Lighten a colour

$colour = '#ae64fe';
$brightness = 0.5; // 50% brighter
$newColour = colourBrightness($colour,$brightness);

Darken a colour

$colour = '#ae64fe';
$brightness = -0.5; // 50% darker
$newColour = colourBrightness($colour,$brightness);

Reader's Comments

  • Thanks for this. I added a small snippet to it to allow for shorthand hex codes… EG. #fff instead of #ffffff.

    // Check if shorthand hex value given (eg. #FFF instead of #FFFFFF)
    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);
    }

  • In the //Darker part of your formula, you do round(0 * (1-$positivePercent));

    Anything times zero will equal zero, so either you can delete that part, or it is wrong.

Leave a Reply

(required)
(will not be published) (required)

The Lab is the web development blog for Clear Pixel that covers many subjects from PHP, CSS, jQuery, CodeIgniter, Design and XHTML / HTML