0

lets say i have the following RGB values:

R:129 G:98 B:87

Photoshop says the saturation of that colour is 33%

How would i work out that percentage using PHP and the RGB values?

Ozzy
  • 10,285
  • 26
  • 94
  • 138

2 Answers2

3

See RGB to HSV in PHP

Taking only the saturation bits from that code, and converting into a percentage:

function saturation($R, $G, $B) {  // 0-255
     $Min = min($R, $G, $B);
     $Max = max($R, $G, $B);
     return $Max == 0 ? 0 : (($Max - $Min) / $Max) * 100;
}

Alternately you could use the original code in the link above - the HSV values it returns are between 0.0 and 1.0, so you just need to multiply the saturation value by 100 to get your percentage.

Community
  • 1
  • 1
rjh
  • 49,276
  • 4
  • 56
  • 63
  • Perfect :) Thanks for rewriting it to be much smaller, running this in every iteration of a 600 * 600 loop :P – Ozzy Mar 05 '10 at 01:08
  • This produces inaccurate results if `255` is not one of the passed values, and errors out if black (`0,0,0`) is passed. Works great if you change the return statement to: `return $Max ? (($Max - $Min) / 255) : 0;` – Stephen M. Harris Jun 24 '14 at 17:39
  • Thanks, I corrected the division by zero. However, I am not sure why the second `$Max` should be replaced with 255, that's not in any other code I can see? – rjh Jun 24 '14 at 19:44
0

PEAR (PHP Extensions And Application Repository) has a nice package called Image_Color2 which allows you do to quick conversions between different color models:

include "Image/Color2.php";

$color = new Image_Color2(array(129,98,87));
$hsv = $color->convertTo('hsv');
$hsvArray = $hsv->getArray();

echo "Hue is " . $hsvArray[0] . "\n";
echo "Saturation is: " . $hsvArray[1] . "\n";
echo "Brightness is: " . $hsvArray[2];    
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175