how to find the hex code for a lighter or darker version of a hex code in php

David Lawrence picture David Lawrence · Jun 18, 2012 · Viewed 7.2k times · Source

I'm trying to achieve what this guy here is doing, only in PHP or jQuery. Basically I have a hex color code, say #FF0000, which is red. How would I find darker or lighter hex color codes of this color.

To clearify: I want to take a hex color code (#FF0000), and find the correct hex color code of lighter or darker shades of that color code.

Either done in PHP, or jQuery, something that I can change the color via PHP, as the server processes the page.

I prefer not to use third party jQuery plugins to achieve this, but I will if its super duper complicated.

Answer

Niet the Dark Absol picture Niet the Dark Absol · Jun 19, 2012

When you say "a lighter version" (or "a darker version") there are a very large number of possibilities. For instance, you could take #ff0000 and have 253 "darker versions" ranging from #010000 to #fe0000. Similarly, you can have 253 "lighter versions" ranging from #ff0101 to #fffefe. So your question is not very well defined.

I will assume in this answer that by "lighter version", you mean the result of overying a 50% transparent white on the colour, and by "darker" the same but black.

In any case, you should always start by extracting the numbers from the hex code:

// assuming input of form "#RRGGBB"
$col = Array(
    hexdec(substr($input,1,2)),
    hexdec(substr($input,3,2)),
    hexdec(substr($input,5,2))
);

Now that you have that, you can easily apply the "overlay":

$darker = Array(
    $col[0]/2,
    $col[1]/2,
    $col[2]/2
);
$lighter = Array(
    255-(255-$col[0])/2,
    255-(255-$col[1])/2,
    255-(255-$col[2])/2
);

Then it's a simple matter to convert them back into hex codes:

$darker = "#".sprintf("%02X%02X%02X", $darker[0], $darker[1], $darker[2]);
$lighter = "#".sprintf("%02X%02X%02X", $lighter[0], $lighter[1], $lighter[2]);

Done!