Search code examples
phpcolorsgdrgbhsv

PHP Work out colour saturation


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?


Solution

  • 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.