Reputation: 439
I have thousands of colors in RGB values saved in my database and I would like to display them in one color chart. But thousands of colors in one chart is not very useful.
Therefore I would like to reduce the number of colors by converting RGB values to 147 HTML named colors . I have to find the best matched HTML color for RGB value, means calculate if RGB value is similar to Crimson or Cyan or Fuchsia or ... Like grouping them by best matched HTML named color. This should be done in PHP.
Feasible?
Upvotes: 2
Views: 661
Reputation: 14243
You can create arrays like this for all colors:
$color=array(100);
$hex=array(100);
$hex[0]=hexdec( "00FFFF" );
$color[0]="Aqua";
$hex[1]=hexdec("F0FFFF");
$color[1]="Azura";
.
.
and then use this code to find nearest value :
function findBestColorMatch($r,$g,$b){
$toSearch=rgb2html($r,$g,$b);
$i=getClosest($toSearch,$hex);
echo $color[$i];
}
function rgb2html($r, $g=-1, $b=-1)
{
if (is_array($r) && sizeof($r) == 3)
list($r, $g, $b) = $r;
$r = intval($r); $g = intval($g);
$b = intval($b);
$r = dechex($r<0?0:($r>255?255:$r));
$g = dechex($g<0?0:($g>255?255:$g));
$b = dechex($b<0?0:($b>255?255:$b));
$color = (strlen($r) < 2?'0':'').$r;
$color .= (strlen($g) < 2?'0':'').$g;
$color .= (strlen($b) < 2?'0':'').$b;
return hexdec($color);
}
function getClosest($search, $hex)
{
$closest = null;
foreach($hex as $item)
{
if($closest == null || abs($search - $closest) > abs($item - $search))
{
$closest = $item;
}
}
return $closest;
}
Upvotes: 2