Skip to content

Instantly share code, notes, and snippets.

@bedeabza
Created April 11, 2014 12:10
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bedeabza/10463089 to your computer and use it in GitHub Desktop.
Save bedeabza/10463089 to your computer and use it in GitHub Desktop.
PHP Hex to HSL and HSL to Hex conversion
function hexToHsl($hex) {
$hex = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
$rgb = array_map(function($part) {
return hexdec($part) / 255;
}, $hex);
$max = max($rgb);
$min = min($rgb);
$l = ($max + $min) / 2;
if ($max == $min) {
$h = $s = 0;
} else {
$diff = $max - $min;
$s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);
switch($max) {
case $rgb[0]:
$h = ($rgb[1] - $rgb[2]) / $diff + ($rgb[1] < $rgb[2] ? 6 : 0);
break;
case $rgb[1]:
$h = ($rgb[2] - $rgb[0]) / $diff + 2;
break;
case $rgb[2]:
$h = ($rgb[0] - $rgb[1]) / $diff + 4;
break;
}
$h /= 6;
}
return array($h, $s, $l);
}
function hslToHex($hsl)
{
list($h, $s, $l) = $hsl;
if ($s == 0) {
$r = $g = $b = 1;
} else {
$q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
$p = 2 * $l - $q;
$r = hue2rgb($p, $q, $h + 1/3);
$g = hue2rgb($p, $q, $h);
$b = hue2rgb($p, $q, $h - 1/3);
}
return rgb2hex($r) . rgb2hex($g) . rgb2hex($b);
}
function hue2rgb($p, $q, $t) {
if ($t < 0) $t += 1;
if ($t > 1) $t -= 1;
if ($t < 1/6) return $p + ($q - $p) * 6 * $t;
if ($t < 1/2) return $q;
if ($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
return $p;
}
function rgb2hex($rgb) {
return str_pad(dechex($rgb * 255), 2, '0', STR_PAD_LEFT);
}
@abillahbd
Copy link

What's the license for this code?

@bedeabza
Copy link
Author

It has no license. I don't remember whether I wrote it myself or found it on the web unlicensed back then. As far as I am concerned, you can use it freely :)

@saltnpixels
Copy link

..I don't think the hext to hsl works right... i don't get the right colors

@vollyimnetz
Copy link

The code of the hslToHex has a small bug. If $s == 0 the rgb values should not be set to 1. The $s value means saturation. If the saturation is zero there is still a luminanz -> meaning there are gray values. A HSL( 0, 0, 0.5) should be RGB( 7f, 7f, 7f ) but here its RGB(ff, ff, ff ).

I wrote a fix - setting a very small value for $s to keep the calculation working:

public static function hslToHex($hsl) {
	list($h, $s, $l) = $hsl;
	if ($s == 0) $s = 0.000001;
		
	$q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
	$p = 2 * $l - $q;

	$r = self::hue2rgb($p, $q, $h + 1/3);
	$g = self::hue2rgb($p, $q, $h);
	$b = self::hue2rgb($p, $q, $h - 1/3);

	return self::rgb2hex($r) . self::rgb2hex($g) . self::rgb2hex($b);
}

@ViniciusBatista32
Copy link

Expected input??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment