rgb2hsl · PHP Function to Convert Colors from RGB to HSL
function rgb2hsl ($r, $g, $b) {
$r_ratio = $r / 255;
$g_ratio = $g / 255;
$b_ratio = $b / 255;
$min = min($r_ratio, $b_ratio, $g_ratio);
$max = max($r_ratio, $b_ratio, $g_ratio);
$l_ratio = ($min + $max) / 2;
$range = $max - $min;
if ($range === 0) return ['h' => 0, 's' => 0, 'l' => 0];
$h_ratio = (function () use ($r_ratio, $g_ratio, $b_ratio, $max, $range) {
if ($max === $r_ratio) return ($g_ratio - $b_ratio) / $range;
if ($max === $g_ratio) return 2 + ($b_ratio - $r_ratio) / $range;
return 4 + ($r_ratio - $g_ratio) / $range;
})();
$s_range = min($l_ratio, 1 - $l_ratio);
return [
'h' => fmod(($h_ratio + 6), 6) * 60,
's' => ($max - $min) / (2 * $s_range) * 100,
'l' => $l_ratio * 100,
];
}
Last updated 3 days ago.