Created
September 3, 2011 23:42
-
-
Save alexkingorg/1191954 to your computer and use it in GitHub Desktop.
Change the brightness of the passed in hex color in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Change the brightness of the passed in color | |
* | |
* $diff should be negative to go darker, positive to go lighter and | |
* is subtracted from the decimal (0-255) value of the color | |
* | |
* @param string $hex color to be modified | |
* @param string $diff amount to change the color | |
* @return string hex color | |
*/ | |
public function hex_color_mod($hex, $diff) { | |
$rgb = str_split(trim($hex, '# '), 2); | |
foreach ($rgb as &$hex) { | |
$dec = hexdec($hex); | |
if ($diff >= 0) { | |
$dec += $diff; | |
} | |
else { | |
$dec -= abs($diff); | |
} | |
$dec = max(0, min(255, $dec)); | |
$hex = str_pad(dechex($dec), 2, '0', STR_PAD_LEFT); | |
} | |
return '#'.implode($rgb); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do you use an if in the loop?
If I'm not mistaken :
$dec -= abs($diff) => $dec -= -$diff (since $diff < 0) => $dec += $diff
So since it would do the same operation anyway, it should be preferable to replace lines 18 to 23 by the addition.
But thank you for that method it helped me generate gradients from any color from the user's theme on my website.