PHP函数将十六进制转换为HSL(非HSL转换为十六进制)

时间:2019-11-19 09:52:28

标签: php colors hex hsl

有人知道如何在PHP中将十六进制颜色转换为HSL吗?我进行了搜索,但是发现的功能无法准确转换颜色。

2 个答案:

答案 0 :(得分:0)

$update=Model:where(..)->Where(..)->Where(..)->update([$updateField => 1]);
 if($update==1)
{

答案 1 :(得分:0)

https://css-tricks.com/converting-color-spaces-in-javascript/的javascript中重写(并进行了一些调整)

<?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) % 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}%)";
}

示例:

<?php

echo hexToHsl('fbffe0'); // outputs 'hsl(68, 100%, 94%)'