Support

Account

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

  • @hube2

    I want to convert the HEX value to HSL. From the following function, when I passed directly the value fff000, then the outcome hsl value is correct, but when I passed #fff000 then the outcome hsl value is incorrect.

    The problem came from #. I wonder how I remove the # from the get_sub_field. As an instance <?php $hex_color = get_sub_field('hex_color');?>

    <?php
    
    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);
        } 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);
        $saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1)));
        if ($saturation < 0) {
            $saturation += 1;
        }
    
        $lightness = round($lightness*100);
        $saturation = round($saturation*100);
    
         return "hsl(${hue}, ${saturation}%, ${lightness}%)";
    
        //return array($hue, $saturation, $lightness);
        }
    $hex_color = 'fff000'; 	
    echo hexToHsl($hex_color);