code: public function countColors($max = null)
  	{
  		if (!imageistruecolor($this->gdResource))
  		{
  			return imagecolorstotal($this->gdResource);
  		}
  
  		$colors = array();
  		$width = imagesx($this->gdResource);
  		$height = imagesy($this->gdResource);
  
  		for ($x = 0; $x < $width; $x++)
  		{
  			for ($y = 0; $y < $height; $y++)
  			{
  				$colors[imagecolorat($this->gdResource, $x, $y)] = true;
  
  				if ($max !== null && \count($colors) > $max)
  				{
  					break 2;
  				}
  			}
  		}
  
  		return \count($colors);
  	}
docs: Count the number of colors in the image
  
  @param integer $max Stop parsing the image if more colors than $max were found
  
  @return integer The number of image colors