Created
January 5, 2021 17:23
-
-
Save hbackman/7a425c84d18556688aa989d0ea858f00 to your computer and use it in GitHub Desktop.
PHP Functions to Convert Hex to RGB & HSL
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
<?php | |
function rgb($hex) | |
{ | |
[$r, $g, $b] = sscanf($hex, "#%02x%02x%02x"); | |
return [$r, $g, $b]; | |
} | |
function hsl($hex) | |
{ | |
$rgb = array_map(function ($dec) { return $dec / 255; }, rgb($hex)); | |
$c_min = min($rgb); | |
$c_max = max($rgb); | |
$c_delta = $c_max - $c_min; | |
if ($c_delta === 0) $hue = 0; | |
else if ($c_max === $rgb[0]) $hue = ( ($rgb[1] - $rgb[2]) / $c_delta ) % 6; | |
else if ($c_max === $rgb[1]) $hue = ( ($rgb[2] - $rgb[0]) / $c_delta ) + 2; | |
else if ($c_max === $rgb[2]) $hue = ( ($rgb[0] - $rgb[1]) / $c_delta ) + 4; | |
if ( ($hue = round($hue * 60)) < 0 ) { | |
$hue += 360; | |
} | |
$lightness = ( ($c_max + $c_min) / 2 ) * 100; | |
$saturation = $c_delta === 0 ? 0 : ( | |
($c_delta / (1 - abs(2 * $lightness - 1)) * 100) | |
); | |
if ($saturation < 0) { | |
$saturation += 100; | |
} | |
$lightness = round($lightness); | |
$saturation = round($saturation); | |
return [ | |
$hue, $saturation, $lightness | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment