PHP function to convert Hex to HSL

PHPServer Side ProgrammingProgramming

The below code can be used to convert hex value into HSL value −

function hex_To_Hsl($hex) {
   $hex_val = array($hex_val[0].$hex_val[1], $hex_val[2].$hex_val[3], $hex_val[4].$hex_val[5]);
   $rgb_val = array_map(function($part) {
      return hexdec($part) / 255;
   }, $hex_val);
   $max_val = max($rgb_val);
   $min_val = min($rgb_val);
   $l = ($max_val + $min_val) / 2;
   if ($max_val == $min_val) {
      $h = $s = 0;
   } else {
      $diff = $max_val - $min_val;
      $s = $l > 0.5 ? $diff / (2 - $max_val - $min_val) : $diff / ($max_val + $min_val);
      switch($max_val) {
         case $rgb_val[0]:
         $h = ($rgb_val[1] - $rgb_val[2]) / $diff + ($rgb_val[1] < $rgb_val[2] ? 6 : 0);
         break;
         case $rgb_val[1]:
         $h = ($rgb_val[2] - $rgb_val[0]) / $diff + 2;
         break;
         case $rgb_val[2]:
         $h = ($rgb_val[0] - $rgb_val[1]) / $diff + 4;
         break;
      }
      $h /= 6;
   }
   return array($h, $s, $l);
}
raja
Published on 06-Apr-2020 11:59:38
Advertisements