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% dar
Here's an example:
<?php
$color = '#aabbcc'; // The color we'll use
Extract the colors. I'd prefer to use regular expressions, though there are probably other more efficient ways too.
if(!preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i', $color, $parts))
die("Not a value color");
Now we have red in $parts[1]
, green in $parts[2]
and blue in $parts[3]
. Now, let's convert them from hexadecimal to integers:
$out = ""; // Prepare to fill with the results
for($i = 1; $i <= 3; $i++) {
$parts[$i] = hexdec($parts[$i]);
Then we'll decrease them by 20 %:
$parts[$i] = round($parts[$i] * 80/100); // 80/100 = 80%, i.e. 20% darker
// Increase or decrease it to fit your needs
Now, we'll turn them back into hexadecimal and add them to our output string
$out .= str_pad(dechex($parts[$i]), 2, '0', STR_PAD_LEFT);
}
Then just add a "#" to the beginning of the string, and that's it!