Skip to content

Instantly share code, notes, and snippets.

@fedetibaldo
Forked from bedeabza/hexhsl.php
Created January 27, 2018 22:18
Show Gist options
  • Save fedetibaldo/3059f986a54ce1a9476743a986648871 to your computer and use it in GitHub Desktop.
Save fedetibaldo/3059f986a54ce1a9476743a986648871 to your computer and use it in GitHub Desktop.
PHP Hex to HSL and HSL to Hex conversion
<?php
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);
}
@JaxProd
Copy link

JaxProd commented Mar 21, 2019

hye and thanks,
hexToHsl doesn't works for me trying with hexToHsl( '#0000FF' ) : (

@fedetibaldo
Copy link
Author

hye and thanks,
hexToHsl doesn't works for me trying with hexToHsl( '#0000FF' ) : (

Removing the hashtag ('#') will do the trick ;)

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