Skip to content

Instantly share code, notes, and snippets.

@chaoszcat
Last active May 23, 2022 05:44
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaoszcat/5325115 to your computer and use it in GitHub Desktop.
Save chaoszcat/5325115 to your computer and use it in GitHub Desktop.
Darken/lighten a hex color programmatically. Originally from http://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color
function shadeColor($color, $percent) {
$num = base_convert(substr($color, 1), 16, 10);
$amt = round(2.55 * $percent);
$r = ($num >> 16) + $amt;
$b = ($num >> 8 & 0x00ff) + $amt;
$g = ($num & 0x0000ff) + $amt;
return '#'.substr(base_convert(0x1000000 + ($r<255?$r<1?0:$r:255)*0x10000 + ($b<255?$b<1?0:$b:255)*0x100 + ($g<255?$g<1?0:$g:255), 10, 16), 1);
}
@Barabashk
Copy link

thank you vary mach

@Aslam97
Copy link

Aslam97 commented May 23, 2022

PHP 8 try

    function shade_color($color, $percent)
    {
        $color = str_replace('#', '', $color);
        $rgb = '';
        if (strlen($color) == 3) {
            $r = hexdec(substr($color, 0, 1) . substr($color, 0, 1));
            $g = hexdec(substr($color, 1, 1) . substr($color, 1, 1));
            $b = hexdec(substr($color, 2, 1) . substr($color, 2, 1));
        } else {
            $r = hexdec(substr($color, 0, 2));
            $g = hexdec(substr($color, 2, 2));
            $b = hexdec(substr($color, 4, 2));
        }
        $rgb = array($r, $g, $b);
        return '#' . implode('', array_map(function ($x) use ($percent) {
            $hex = dechex($x);
            return str_pad(
                dechex(
                    round(
                        hexdec($hex) +
                            round(
                                (
                                    (255 - hexdec($hex)) * $percent
                                ) / 100
                            )
                    )
                ),
                2,
                '0',
                STR_PAD_LEFT
            );
        }, $rgb));
    }

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