Basically this.
Code: Select all
NAMESPACE color
FUNCTION luminance($hex, $lum=0) {
// validate hex color
$hex = regexreplace($hex, '^#', '');
assert (strlen($hex) == 6) || (strlen($hex) == 3) || regexmatches($hex, '[^0-9a-f]'), "incorrect hex color: $hex";
$hex = (strlen($hex) == 3) ? strrepeat(substr($hex, 0, 1), 2) . strrepeat(substr($hex, 1, 1), 2) . strrepeat(substr($hex, 2, 1), 2) : $hex;
// apply luminance
$result = '#'; $i = 0;
while ($i++ < 3) {
$color = hextodec(substr($hex, 2*($i-1), 2));
$color = dectohex(round(math::min(math::max($color + ($color * $lum), 0), 255)));
$result .= substr("00" . $color, -2);
}
return $result;
}
NAMESPACE math
FUNCTION max($x, $y) { return ($x >= $y) ? $x : $y; }
FUNCTION min($x, $y) { return ($x <= $y) ? $x : $y; }
"test"
echo color::luminance("#69c", 0); // returns "#6699cc"
echo color::luminance("6699CC", 0.2); // "#7ab8f5" - 20% lighter
echo color::luminance("69C", -0.5); // "#334d66" - 50% darker
echo color::luminance("000", 1); // "#000000" - true black cannot be made lighter!
[edited: reduce LOC. fix small miscalculation]