hsl2rgb · PHP Function to Convert Colors from HSL to RGB

Home | See also: hsl2rgb JavaScript Function
function hsl2rgb ($h, $s, $l) {

    $h_ratio = fmod(fmod($h, 360) + 360, 360) / 30;
    $s_ratio = max(0, min(1, $s / 100));
    $l_ratio = max(0, min(1, $l / 100));
    $range = $s_ratio * min($l_ratio, 1 - $l_ratio);

    $calculate = function ($offset) use ($h_ratio, $l_ratio, $range) {
        $x = $h_ratio + 12 - $offset % 12;
        $value = max(3 - $x, $x - 9);
        $clipped = max(-1, min(1, $value));
        return (int)round(($l_ratio + $clipped * $range) * 255);
    };

    return [
        'r' => $calculate(0),
        'g' => $calculate(4),
        'b' => $calculate(8),
    ];

}
Last updated 19 days ago.
nichabi.com