Support

Account

Home Forums Front-end Issues Convert hexadecimal value to HSL Reply To: Convert hexadecimal value to HSL

  • @hube2 I am back after a while.

    I believed that code worked, but it’s something missing right here..

    function hexToHsl($hex){
        $red = hexdec(substr($hex, 0, 2)) / 255;
        $green = hexdec(substr($hex, 2, 2)) / 255;
        $blue = hexdec(substr($hex, 4, 2)) / 255;
    
        $cmin = min($red, $green, $blue);
        $cmax = max($red, $green, $blue);
        $delta = $cmax - $cmin;
    
        if ($delta === 0) {
            $hue = 0;
        } elseif ($cmax === $red) {
            $hue = (($green - $blue) / $delta) % 6;
        } elseif ($cmax === $green) {
            $hue = ($blue - $red) / $delta + 2;
        } else {
            $hue = ($red - $green) / $delta + 4;
        }
    
        $hue = round($hue * 60);
        if ($hue < 0) {
            $hue += 360;
        }
    
        $lightness = (($cmax + $cmin) / 2) * 100;
        $saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1))) * 100;
        if ($saturation < 0) {
            $saturation += 100;
        }
    
        $lightness = round($lightness);
        $saturation = round($saturation);
    
        return "hsl(${hue}, ${saturation}%, ${lightness}%)";
        }

    usage

    <?php echo '',print_r(hexToHsl($hex_color)).'';?>

    Returns : hsl(137, 99%, 42%)1 but the correct is hsl(258, 83%, 45%). What exactly I’m doing wrong? Any kind of help is much appreciated.

    Sincerely,
    Mike