Click to See Complete Forum and Search --> : Color Conversion Functions


MikeSnead
05-23-2005, 01:58 AM
Not exactly the most well formed code (I wrote it back when I had fun compressing scripts as much as I could) but it has so far worked well. Thought it might be useful for someone someday for some strange reason :)

Convert back and forth between RGB and Hue/Sat/Brightness color values.


<?php

function RGB_to_HSV ( $r , $g , $b )
{
$r = $r/255;
$g = $g/255;
$b = $b/255;

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

if ($MAX == $MIN) return array(0,0,$MAX);
if ($r == $MAX) $HUE = ((0 + (($g - $b)/($MAX-$MIN))) * 60);
elseif ($g == $MAX) $HUE = ((2 + (($b - $r)/($MAX-$MIN))) * 60);
elseif ($b == $MAX) $HUE = ((4 + (($r - $g)/($MAX-$MIN))) * 60);
if ( $HUE < 0 ) $HUE += 360;

return array($HUE,(($MAX - $MIN)/$MAX),$MAX);
}

function HSV_to_RGB ( $H , $S , $V )
{
if ($S == 0) return array($V * 255,$V * 255,$V * 255);

$Hi = floor($H/60);
$f = (($H/60) - $Hi);
$p = ($V * (1 - $S));
$q = ($V * (1 - ($S * $f)));
$t = ($V * (1 - ($S * (1 - $f))));

switch ( $Hi )
{
case 0 : $red = $V; $gre = $t; $blu = $p; break;
case 1 : $red = $q; $gre = $V; $blu = $p; break;
case 2 : $red = $p; $gre = $V; $blu = $t; break;
case 3 : $red = $p; $gre = $q; $blu = $V; break;
case 4 : $red = $t; $gre = $p; $blu = $V; break;
case 5 : $red = $V; $gre = $p; $blu = $q; break;
default : exit("error -- invalid parameters\n\n");
}

return array(round($red * 255),round($gre * 255),round($blu * 255));
}

?>

BuzzLY
06-10-2005, 03:46 PM
I use very similar code in my color picker. Click on the link in my signature.

leatherback
06-10-2005, 06:04 PM
Hey Buzz,

That is a great tool!

Cool. Is the code free/available? Or..?

j.

BuzzLY
06-11-2005, 06:21 AM
Thanks.

Yes, you can use it if you like. There is a zip file available -- just click one of the links at the bottom of the Color Picker page.

I don't warrant the code -- use it as is, and modify how you like. All I ask is that you give me credit for the original code, and let me know when you modify it so I can check it out!