pic most common colors from an image

Discussion in 'PHP' started by falcondriver, Nov 5, 2007.

  1. #1
    hi

    i wanna create a css-file for my site based on a image. now i need a function that can grab the 4-6 most common colors from any given image - something like colorhunter.com .
    i have like ~100 pictures, and i dont wanna run them all thru colorhunter :)
    had anyone an idea how this is done???
     
    falcondriver, Nov 5, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Here you go. Just note that this function is slow and memory consuming.

    
    <?php
    
    function imagemostcommoncolor($source, $num_colors = 10)
    {
    	if (!$image = @imagecreatefromjpeg($source))
    	{
    		trigger_error("Unable to open image {$source}", E_USER_WARNING);
    		return false;
    	}
    
    	$width = imagesx($image);
    	$height = imagesy($image);
    	$colors = array();
    	
    	for ($x = 0; $x < $width; $x++)
    	{
    		for ($y = 0; $y < $height; $y++)
    		{
    			$index = imagecolorat($image, $x, $y);
    			$rgb = imagecolorsforindex($image, $index);
    			$hexcolor = rgbhex($rgb['red'], $rgb['green'], $rgb['blue']);
    			
    			if (isset($colors[$hexcolor]))
    			{
    				$colors[$hexcolor]++;
    			}
    			else
    			{
    				$colors[$hexcolor] = 1;
    			}
    		}
    	}
    	
    	arsort($colors);
    	array_splice($colors, $num_colors);
    	return array_keys($colors);
    }
    
    function rgbhex($red, $green, $blue)
    {
    	return sprintf('%02X%02X%02X', $red, $green, $blue);
    }
    
    PHP:

    It returns the 10 most common colors of the image (Unless you specify another amount in the second, optional parameter).

    Usage example:
    
    
    $colors = imagemostcommoncolor('path/to/image.jpg');
    
    foreach ($colors AS $color)
    {
    	echo '<span style="color: #', $color, ';">', $color, "</span><br />\n";
    }
    
    PHP:
     
    nico_swd, Nov 6, 2007 IP
    falcondriver likes this.
  3. falcondriver

    falcondriver Well-Known Member

    Messages:
    963
    Likes Received:
    47
    Best Answers:
    0
    Trophy Points:
    145
    #3
    hm thanks, i had something like this in mind as well (get the color for each single pixel...), guess there is no "used colors" palette you could just read out for gif or png file?
     
    falcondriver, Nov 8, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Not that I know of.
     
    nico_swd, Nov 8, 2007 IP