【问题标题】:PHP function to convert Hex to HSL (Not HSL to Hex)PHP函数将十六进制转换为HSL(不是HSL到十六进制)
【发布时间】:2019-11-19 09:52:28
【问题描述】:

有谁知道如何在 PHP 中将十六进制颜色转换为 HSL?我已经搜索过,但我发现的函数不能精确地转换颜色。

【问题讨论】:

标签: php colors hex hsl


【解决方案1】:
function hexToHsl($hex) {
    $hex = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
    $rgb = array_map(function($part) {
        return hexdec($part) / 255;
    }, $hex);

    $max = max($rgb);
    $min = min($rgb);

    $l = ($max + $min) / 2;

    if ($max == $min) {
        $h = $s = 0;
    } else {
        $diff = $max - $min;
        $s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);

        switch($max) {
            case $rgb[0]:
                $h = ($rgb[1] - $rgb[2]) / $diff + ($rgb[1] < $rgb[2] ? 6 : 0);
                break;
            case $rgb[1]:
                $h = ($rgb[2] - $rgb[0]) / $diff + 2;
                break;
            case $rgb[2]:
                $h = ($rgb[0] - $rgb[1]) / $diff + 4;
                break;
        }

        $h /= 6;
    }

    return array($h, $s, $l);
}

【讨论】:

  • 您可能希望显示此脚本的原始source...
  • 这个我已经试过了。它不适用于某些颜色。例如,对于#fbffe0,HSL 应该是 (68, 100%, 94%),而函数的情况并非如此。
【解决方案2】:

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%)'

【讨论】:

  • 感谢您的回复。虽然它适用于# fbffe0,但它不适用于某些颜色。例如,对于#f5efe1,HSL 应该是 (42, 50%, 92%),而函数返回 hsl (0, 100%, 92%)。黄色的阴影变成了粉色的阴影。
猜你喜欢
  • 2017-05-15
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 2015-06-25
  • 2020-01-08
  • 2015-01-26
  • 1970-01-01
相关资源
最近更新 更多