2

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?

Linda
  • 419
  • 1
  • 4
  • 12
  • 2
    There is similar question answered already, http://stackoverflow.com/questions/1847092/given-an-rgb-value-what-would-be-the-best-way-to-find-the-closest-match-in-the-d – mpapec May 05 '13 at 08:45
  • This is not exactly what I need but helpful. For my purpose I will try the approach of passing all RGB values in one true color image, then reduce the number of colors in this image to the number I want and then extract all the colors from the resulting image, counting how often they are used in percent. Not sure if this would work, just an idea. – Linda May 05 '13 at 08:52

1 Answers1

2

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;
}

from here & here

Community
  • 1
  • 1
Majid
  • 13,853
  • 15
  • 77
  • 113