好的,忘记前面的代码,这是我从几个来源汇总的更可靠的版本,它也使用更常见的 0-360 作为色调。
我还添加了一个测试小程序,它选择随机颜色然后“告诉”你它们是什么!
似乎更可靠,可能需要围绕截止值进行一些摆弄(尤其是橙色/灰色等)。我使用这个在线颜色选择器进行测试。
<?php
function RGBtoHSL($r,$g,$b) {
// based on code and formulas from:
// http://www.had2know.com/technology/hsl-rgb-color-converter.html
// http://colorgrader.net/index.php/dictionary-a-tutorials/color-theory/93-math-behind-colorspace-conversions-rgb-hsl.html
// http://proto.layer51.com/d.aspx?f=1135
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$d = ($max - $min) / 255;
$lum = round((($max+$min)/2)/255, 2);
$sat = 0;
if ($lum > 0) $sat = round($d/(1 - (2*$lum-1)), 2);
$hue = 0;
if(($r==$g) && ($g==$b)) $hue = 0;
else if($r>=$g && $g>=$b) $hue = 60*($g-$b)/($r-$b);
else if($g>=$r && $r>=$b) $hue = 60 + 60*($g-$r)/($g-$b);
else if($g>=$b && $b>=$r) $hue = 120 + 60*($b-$r)/($g-$r);
else if($b>=$g && $g>=$r) $hue = 180 + 60*($b-$g)/($b-$r);
else if($b>=$r && $r>=$g) $hue = 240 + 60*($r-$g)/($b-$g);
else if($r>=$b && $b>=$g) $hue = 300 + 60*($r-$b)/($r-$g);
else $hue = 0;
$hue = round($hue, 0);
$hsl = array();
$hsl['h'] = $hue;
$hsl['s'] = $sat;
$hsl['l'] = $lum;
return $hsl;
}
// example: pick 42 random colours then identify them
echo "<div style='float: left; width: 1000px;'>";
srand;
for ($f=0; $f < 42; $f++) {
$red = rand(0, 255);
$green = rand(0, 255);
$blue = rand(0, 255);
$hsl = RGBtoHSL($red, $green, $blue);
$hue = $hsl['h'];
$sat = $hsl['s'];
$lum = $hsl['l'];
$colour = "Red"; // default to red
if ($hue >= 11 && $hue <= 45) {
$colour = "Orange";
if ($lum < 0.51) $colour = "Brown";
}
if ($hue >= 46 && $hue <= 62) $colour = "Yellow";
if ($hue >= 63 && $hue <= 160) $colour = "Green";
if ($hue >= 161 && $hue <= 262) $colour = "Blue";
if ($hue >= 263 && $hue <= 292) $colour = "Purple";
if ($hue >= 293 && $hue <= 349) $colour = "Pink";
if ($sat < 0.07) $colour = "Grey"; // do grey before black/white
if ($lum < 0.10) $colour = "Black";
if ($lum > 0.97) $colour = "White";
echo "<div style='float: left; width: 150px; border: 1px solid #000000; margin: 5px;'>";
echo "<div style='float: left; width: 20px; height: 120px; background-color: rgb($red, $green, $blue); margin-right: 10px;'></div>";
echo "<p style='width: 33%; float: left;'>R=$red<br/>G=$green<br/>B=$blue</p>";
echo "<p style='width: 33%; float: right;'>H=$hue<br/>S=$sat<br/>L=$lum</p>";
echo "<p><b>$colour</b></p>";
echo "</div>";
}
echo "</div>";
?>