Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

colors - PHP HSV to RGB formula comprehension

I can convert RGB values to HSV with the following code...

 $r = $r/255;
 $g = $g/255;
 $b = $b/255;

 $h = 0;
 $s = 0;
 $v = 0;

 $min = min(min($r, $g),$b);
 $max = max(max($r, $g),$b);

 $r = $max-$min;
 $v = $max;


 if($r == 0){
  $h = 0;
  $s = 0;
 }
 else {
  $s = $r / $max;

  $hr = ((($max - $r) / 6) + ($r / 2)) / $r;
  $hg = ((($max - $g) / 6) + ($r / 2)) / $r;
  $hb = ((($max - $b) / 6) + ($r / 2)) / $r;

  if ($r == $max) $h = $hb - $hg;
  else if($g == $max) $h = (1/3) + $hr - $hb;
  else if ($b == $max) $h = (2/3) + $hg - $hr;

  if ($h < 0)$h += 1;
  if ($h > 1)$h -= 1;
 }

But how do you convert HSV to RGB in PHP???

The following is on wikipedia but I don't understand it,

I'm guessing it's pretty obvious

alt text

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is for the the HSV values in the range [0,1] (and giving RGB values in the range [0,1], instead of {0, 1, ..., 255}:

function HSVtoRGB(array $hsv) {
    list($H,$S,$V) = $hsv;
    //1
    $H *= 6;
    //2
    $I = floor($H);
    $F = $H - $I;
    //3
    $M = $V * (1 - $S);
    $N = $V * (1 - $S * $F);
    $K = $V * (1 - $S * (1 - $F));
    //4
    switch ($I) {
        case 0:
            list($R,$G,$B) = array($V,$K,$M);
            break;
        case 1:
            list($R,$G,$B) = array($N,$V,$M);
            break;
        case 2:
            list($R,$G,$B) = array($M,$V,$K);
            break;
        case 3:
            list($R,$G,$B) = array($M,$N,$V);
            break;
        case 4:
            list($R,$G,$B) = array($K,$M,$V);
            break;
        case 5:
        case 6: //for when $H=1 is given
            list($R,$G,$B) = array($V,$M,$N);
            break;
    }
    return array($R, $G, $B);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...