Skip to content

Instantly share code, notes, and snippets.

@alexkingorg
Created September 3, 2011 23:42
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexkingorg/1191954 to your computer and use it in GitHub Desktop.
Save alexkingorg/1191954 to your computer and use it in GitHub Desktop.
Change the brightness of the passed in hex color in PHP
<?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);
}
@clofab
Copy link

clofab commented Jun 5, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment