Hello . I have a code of color. For example #202010 . How to generate a new color code which is either lighter or darker by 20% (or given x%) in php.? Please help me . I see a sample in javascript but i don't understand it. PLEASE HELP ME
+2
A:
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!
Frxstrem
2010-08-18 13:11:36