SassColour::rgb2hsl PHP Method

rgb2hsl() public method

Converts from RGB to HSL colourspace Algorithm adapted from {@link http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript}
public rgb2hsl ( )
    public function rgb2hsl()
    {
        list($r, $g, $b) = array($this->red / 255, $this->green / 255, $this->blue / 255);
        $max = max($r, $g, $b);
        $min = min($r, $g, $b);
        $d = $max - $min;
        if ($max == $min) {
            $h = 0;
            $s = 0;
        } elseif ($max == $r) {
            $h = 60 * ($g - $b) / $d;
        } else {
            if ($max == $g) {
                $h = 60 * ($b - $r) / $d + 120;
            } else {
                if ($max == $b) {
                    $h = 60 * ($r - $g) / $d + 240;
                }
            }
        }
        $l = ($max + $min) / 2;
        if ($l > 0.5) {
            $s = 2 - $max - $min != 0 ? $d / (2 - $max - $min) : 0;
        } else {
            $s = $max + $min != 0 ? $d / ($max + $min) : 0;
        }
        while ($h > 360) {
            $h -= 360;
        }
        while ($h < 0) {
            $h += 360;
        }
        $this->hue = $h;
        $this->saturation = $s * 100;
        $this->lightness = $l * 100;
    }

Usage Example

 /**
  * Scales one or more property of the color by the percentage requested.
  *
  * @param SassColour $color the colour to adjust
  * @param int        $red
  * @param int        $green
  * @param int        $blue
  * @param int        $saturation
  * @param int        $lightness
  * @param int        $alpha
  *
  * @internal param $SassNumber (red, green, blue, saturation, lightness, alpha) - the amount(s) to scale by
  * @return SassColour
  */
 public static function scale_color($color, $red = 0, $green = 0, $blue = 0, $saturation = 0, $lightness = 0, $alpha = 0)
 {
     $maxes = array('red' => 255, 'green' => 255, 'blue' => 255, 'saturation' => 100, 'lightness' => 100, 'alpha' => 1);
     $color->rgb2hsl();
     foreach ($maxes as $property => $max) {
         $obj = ${$property};
         $scale = 0.01 * $obj->value;
         $diff = $scale > 0 ? $max - $color->{$property} : $color->{$property};
         $color->{$property} = $color->{$property} + $diff * $scale;
     }
     $color->hsl2rgb();
     return $color;
 }