-
-
Save OrinZ/5fdf63dcc95f3a9bfee77414a6b9dd61 to your computer and use it in GitHub Desktop.
PHP snippet to convert RGB hex to HSL array, and HSL array to RGB hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
function rgb2hsl( $rgb ) { | |
$rgb = trim($rgb, '#'); | |
if( strlen($rgb) == 6) | |
$rgb = str_split($rgb, 2); | |
elseif( strlen($rgb) == 3) | |
$rgb = array($rgb[0] . $rgb[0], $rgb[1] . $rgb[1], $rgb[2] . $rgb[2]); | |
foreach($rgb as &$value) | |
$value = hexdec($value) / 255; | |
$max = max( $rgb ); | |
$min = min( $rgb ); | |
$h; | |
$s; | |
$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 $rgb[0]: | |
$h = 60 * fmod( ( ( $rgb[1] - $rgb[2] ) / $d ), 6 ); | |
if ($rgb[2] > $rgb[1]) { | |
$h += 360; | |
} | |
break; | |
case $rgb[1]: | |
$h = 60 * ( ( $rgb[2] - $rgb[0] ) / $d + 2 ); | |
break; | |
case $rgb[2]: | |
$h = 60 * ( ( $rgb[0] - $rgb[1] ) / $d + 4 ); | |
break; | |
} | |
} | |
// return array( round( $h, 3 ), round( $s, 3 ), round( $l, 3 ) ); | |
return array( $h, $s, $l ); | |
} | |
function hsl2rgb( $h, $s, $l ){ | |
$r; | |
$g; | |
$b; | |
$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 = str_pad(dechex(round(( $r + $m ) * 255)), 2, '0', STR_PAD_LEFT) ; | |
$g = str_pad(dechex(round(( $g + $m ) * 255)), 2, '0', STR_PAD_LEFT) ; | |
$b = str_pad(dechex(round(( $b + $m ) * 255)), 2, '0', STR_PAD_LEFT) ; | |
return $r . $g . $b; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment