Jump to content

Returning a list of colors used in an image.


rgrne

Recommended Posts

Is there some PHP function that will look at all the pixels in an image and return a list or table of all the colors used in that image?  Alternatively, is there a function that will return the color of just one pixel identified by row and column?  If so I could write my own script to check all the values. 

 

 

 

I created a little script that detects what color someone clicks on in an image and determines if it's closer to black or white. Maybe it will help:

 

<?php
if($_POST) {
$im=imagecreatefrompng("images/test_image.png");
$color=imagecolorat($im,$_POST['submit_x'],$_POST['submit_y']);
$r = dechex(($color >> 16) & 0xFF);
$g = dechex(($color >>  & 0xFF);
$b = dechex($color & 0xFF);
if(strlen($r)<2) $r="0".$r;
if(strlen($g)<2) $g="0".$g;
if(strlen($b)<2) $b="0".$b;

$detect=imagecreate(1,1);
imagecolorallocate($detect,0xFF,0xFF,0xFF);
imagecolorallocate($detect,0x00,0x00,0x00);
$detect_color=imagecolorclosest($detect,hexdec($r),hexdec($g),hexdec($b));
imagefilledrectangle($detect,0,0,imagesx($detect),imagesy($detect),$detect_color);
echo "<span style=\"background:#".$r.$g.$b."; color:".($detect_color?"#FFF":"#000").";\">".$r.$g.$b."</span><br />";
}
?><form method="post" action="test.php">
<input name="submit" type="image" value="Submit" src="images/test_image.png" alt="choose a color" onmouseover="this.style.cursor='crosshair';" onmouseout="this.style.cursor='auto'" />
</form>

you could loop over all pixels, saving the colors to an array:

 

$im=imagecreatefrompng("images/test_image.png");

$all_colors = array();
for ($x=1;$x<=$pixel_width;$x++) {
     for ($y=1;$y<=$pixel_height;$y++) {
          $color=imagecolorat($im,$x,$y);
          $all_colors[$color] = 1;
     }
}

// the keys of $all_colors are unique colors.

imagecolorat() will only give the index of the color in the palette for paletted images such as gif.

 

<?php
$im = imagecreatefromgif('baa.gif');

$colors = array();
for ($x=0, $w = imagesx($im); $x < $w; $x++)
{
    for ($y=0, $h = imagesy($im); $y < $h; $y++)
    {
        $c = imagecolorat($im, $x, $y);
        $a = imagecolorsforindex($im, $c);
        $colors[vsprintf('%02X%02X%02X', $a)] = 1;
    }
}
ksort ($colors, SORT_STRING);
echo "<table>\n";
foreach ($colors as $col=>$v)
{
    echo "<tr><td style='background-color:#$col; width:50px'> </td><td>$col</td></tr>\n";
}
echo "</table>\n";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.