HSL to RGB color conversion

后端 未结 21 2737
忘了有多久
忘了有多久 2020-11-22 01:59

I am looking for a JavaScript / PHP algorithm to convert between HSL color to RGB.

It seems to me that HSL is not very widely used so I am not having much luck search

21条回答
  •  梦毁少年i
    2020-11-22 02:25

    PHP implementation of @Mohsen's code (including Test!)

    Sorry to re-post this. But I really haven't seen any other implementation that gives the quality I needed.

    /**
     * Converts an HSL color value to RGB. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes h, s, and l are contained in the set [0, 1] and
     * returns r, g, and b in the set [0, 255].
     *
     * @param   {number}  h       The hue
     * @param   {number}  s       The saturation
     * @param   {number}  l       The lightness
     * @return  {Array}           The RGB representation
     */
      
    function hue2rgb($p, $q, $t){
                if($t < 0) $t += 1;
                if($t > 1) $t -= 1;
                if($t < 1/6) return $p + ($q - $p) * 6 * $t;
                if($t < 1/2) return $q;
                if($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
                return $p;
            }
    function hslToRgb($h, $s, $l){
        if($s == 0){
            $r = $l;
            $g = $l;
            $b = $l; // achromatic
        }else{
            $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
            $p = 2 * $l - $q;
            $r = hue2rgb($p, $q, $h + 1/3);
            $g = hue2rgb($p, $q, $h);
            $b = hue2rgb($p, $q, $h - 1/3);
        }
    
        return array(round($r * 255), round($g * 255), round($b * 255));
    }
    
    /* Uncomment to test * /
    for ($i=0;$i<360;$i++) {
      $rgb=hslToRgb($i/360, 1, .9);
      echo '
    '; } /* End Test */

提交回复
热议问题