Jump to content

PHP function to convert Hex to HSL (Not HSL to Hex)


thara

Recommended Posts

I am trying to convert colors from Hex to HSL (Not HSL to Hex). I am using a PHP function for this purpose. But It's not working properly for some colors. For example for #e04c4c the HSL should be (0, 70%, 59%) which it isn't the case with the function.

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}%)";
    return array($hue, $saturation, $lightness);
}

This is how I used it:
 

$templatePrimaryColor = '#e04c4c';

$templatePrimaryColor = str_replace("#", "",$templatePrimaryColor);

list($h,$s,$l) = hexToHsl($templatePrimaryColor);

$primaryColor = "hsl(${h}, ${s}%, ${l}%)";

This is the output:

echo '<pre>',print_r(hexToHsl($templatePrimaryColor)).'</pre>';

Array
(
    [0] => 0
    [1] => 99
    [2] => 59
)
1

Does anyone know what is the problem there?

Thank you.

Link to comment
Share on other sites

    $lightness = (($cmax + $cmin) / 2) * 100;
    $saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1))) * 100;

You're multiplying the lightness by 100 too early. This throws off the saturation calculation.

Leave it as $cmax+$cmin/2 and multiply when you do the round() later.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.