Kirki_Color::rgb_to_hsv PHP Method

rgb_to_hsv() public static method

Convert hex color to hsv.
public static rgb_to_hsv ( string $color = [] ) : array
$color string The rgb color to convert array( 'r', 'g', 'b' ).
return array Returns array( 'h', 's', 'v' ).
        public static function rgb_to_hsv($color = array())
        {
            $var_r = $color[0] / 255;
            $var_g = $color[1] / 255;
            $var_b = $color[2] / 255;
            $var_min = min($var_r, $var_g, $var_b);
            $var_max = max($var_r, $var_g, $var_b);
            $del_max = $var_max - $var_min;
            $h = 0;
            $s = 0;
            $v = $var_max;
            if (0 != $del_max) {
                $s = $del_max / $var_max;
                $del_r = (($var_max - $var_r) / 6 + $del_max / 2) / $del_max;
                $del_g = (($var_max - $var_g) / 6 + $del_max / 2) / $del_max;
                $del_b = (($var_max - $var_b) / 6 + $del_max / 2) / $del_max;
                if ($var_r == $var_max) {
                    $h = $del_b - $del_g;
                } elseif ($var_g == $var_max) {
                    $h = 1 / 3 + $del_r - $del_b;
                } elseif ($var_b == $var_max) {
                    $h = 2 / 3 + $del_g - $del_r;
                }
                if ($h < 0) {
                    $h++;
                }
                if ($h > 1) {
                    $h--;
                }
            }
            return array('h' => round($h, 2), 's' => round($s, 2), 'v' => round($v, 2));
        }

Usage Example

Esempio n. 1
0
 public function test_rgb_to_hsv()
 {
     $white = array('h' => 0, 's' => 0, 'v' => 1);
     $black = array('h' => 0, 's' => 0, 'v' => 0);
     $red = array('h' => 0, 's' => 1, 'v' => 1);
     $green = array('h' => 0.33, 's' => 1, 'v' => 1);
     $blue = array('h' => 0.67, 's' => 1, 'v' => 1);
     $this->assertEquals($white, Kirki_Color::rgb_to_hsv(array(255, 255, 255)));
     $this->assertEquals($black, Kirki_Color::rgb_to_hsv(array(0, 0, 0)));
     $this->assertEquals($red, Kirki_Color::rgb_to_hsv(array(255, 0, 0)));
     $this->assertEquals($green, Kirki_Color::rgb_to_hsv(array(0, 255, 0)));
     $this->assertEquals($blue, Kirki_Color::rgb_to_hsv(array(0, 0, 255)));
 }