Contao\GdImage::countColors PHP Method

countColors() public method

Count the number of colors in the image
public countColors ( integer $max = null ) : integer
$max integer Stop parsing the image if more colors than $max were found
return integer The number of image colors
    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);
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * Tests the countColors() method.
  */
 public function testCountColors()
 {
     $image = imagecreatetruecolor(100, 100);
     imagealphablending($image, false);
     imagefill($image, 0, 0, imagecolorallocatealpha($image, 255, 0, 0, 0));
     imagefilledrectangle($image, 50, 0, 100, 50, imagecolorallocatealpha($image, 0, 255, 0, 0));
     imagefilledrectangle($image, 0, 50, 50, 100, imagecolorallocatealpha($image, 0, 0, 255, 0));
     imagefilledrectangle($image, 50, 50, 100, 100, imagecolorallocatealpha($image, 0, 0, 0, 127));
     $image = new GdImage($image);
     $this->assertEquals(4, $image->countColors());
     $this->assertEquals(4, $image->countColors(256));
     $this->assertEquals(2, $image->countColors(1));
 }