Skip to content

Instantly share code, notes, and snippets.

@StephanWeinhold
Forked from brandonheyer/rgbToHSL.php
Last active September 27, 2016 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephanWeinhold/d9000e82aa57a8330b71e39f1e861508 to your computer and use it in GitHub Desktop.
Save StephanWeinhold/d9000e82aa57a8330b71e39f1e861508 to your computer and use it in GitHub Desktop.
PHP snippet to convert RGB to HSL and HSL to RGB.
<?php
function rgbToHsl($r, $g, $b)
{
$r /= 255;
$g /= 255;
$b /= 255;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$l = ($max + $min) / 2;
$d = $max - $min;
if ($d == 0) {
$h = $s = 0; // achromatic
}
else {
$s = $d / (1 - abs(2 * $l - 1));
switch ($max) {
case $r:
$h = 60 * fmod((($g - $b) / $d), 6);
if ($b > $g) {
$h += 360;
}
break;
case $g:
$h = 60 * (($b - $r) / $d + 2);
break;
case $b:
$h = 60 * (($r - $g ) / $d + 4);
break;
}
}
return [round($h, 2), round($s, 2), round($l, 2)];
}
function hslToRgb($h, $s, $l)
{
$c = (1 - abs(2 * $l - 1)) * $s;
$x = $c * (1 - abs(fmod(($h / 60), 2) - 1));
$m = $l - ($c / 2);
if ($h < 60) {
$r = $c;
$g = $x;
$b = 0;
}
else if ($h < 120) {
$r = $x;
$g = $c;
$b = 0;
}
else if ($h < 180) {
$r = 0;
$g = $c;
$b = $x;
}
else if ($h < 240) {
$r = 0;
$g = $x;
$b = $c;
}
else if ($h < 300) {
$r = $x;
$g = 0;
$b = $c;
}
else {
$r = $c;
$g = 0;
$b = $x;
}
$r = ($r + $m) * 255;
$g = ($g + $m) * 255;
$b = ($b + $m) * 255;
return [floor($r), floor($g), floor($b)];
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment