Pop\Image\Gd::getColors PHP Method

getColors() public method

Return all of the colors in the palette in an array format
public getColors ( integer | string $format = Pop\Image\Gd::HEX ) : array
$format integer | string
return array
    public function getColors($format = \Pop\Image\Gd::HEX)
    {
        // Initialize the colors array and the image resource.
        $colors = array();
        $this->createResource();
        // Loop through each pixel of the image, recording the color result
        // in the color array.
        for ($h = 0; $h < $this->height; $h++) {
            for ($w = 0; $w < $this->width; $w++) {
                // Get the color index at the pixel location, translating
                // into human readable form.
                $color_index = imagecolorat($this->resource, $w, $h);
                $color_trans = imagecolorsforindex($this->resource, $color_index);
                // Convert to the proper HEX or RGB format.
                if ($format) {
                    $rgb = sprintf('%02s', dechex($color_trans['red'])) . sprintf('%02s', dechex($color_trans['green'])) . sprintf('%02s', dechex($color_trans['blue']));
                } else {
                    $rgb = $color_trans['red'] . "," . $color_trans['green'] . "," . $color_trans['blue'];
                }
                // If the color is not already in the array, add to it.
                if (!in_array($rgb, $colors)) {
                    $colors[] = $rgb;
                }
            }
        }
        // Destroy the image resource.
        $this->destroy();
        // Return the colors array.
        return $colors;
    }

Usage Example

示例#1
0
 public function testGetColors()
 {
     $i = new Gd(__DIR__ . '/../tmp/test.gif');
     $hex = $i->getColors();
     $rgb = $i->getColors(false);
     $this->assertEquals(16, count($hex));
     $this->assertEquals(16, count($rgb));
     $this->assertTrue(in_array('113405', $hex));
     $this->assertTrue(in_array('17,52,5', $rgb));
 }