Generating a color palette from a image in php

In the previous post we saw how we can generate a screenshot from a url. In this post we will see how we can create a color palette of the screenshot (or any other image for that matter) using PHP and GD. This can be useful if you need to quickly get the color scheme of a website or a image. Below are a few example images and their palettes generated using the program.

Images: Flickr

Creating a palette

The palette script requires the GD library to be installed on your system. These days the GD library is installed on most PHP systems; but if it is disabled you need to enable it in your php.ini. Make sure that the following line is set in your php.ini.


Next download the palette class from below, which includes a test picture and a test php script. The original palette class from which the examples are created can be found at github, but the below download includes all the necessary files to create a palette.

Download Source
Downloads : [downloadcounter(palette)] / File size : [downloadsize(palette)]

The php script creates a palette of the most common colors found in the image. Try using various grid sizes to see how the palette looks. Hovering on each color cell will display the corresponding color value.

The code

The skeleton of the example code is shown below:

image = $image_to_read;
$colors = $pal->Get_Color();

The $colors variable now holds an array of colors, the most common colors being at the top. We can now iterate through the array and display the colors using various methods. In the example code included in the download, I’ve used a html table to display the palette.

        [f0f0f0] => 3598
        [e0e0e0] => 1803
        [f0f0e0] => 326
        [e0e0c0] => 141
        [c0c0c0] => 110
        [404040] => 67

The complete example code is shown below.

image = $image_to_read;
$colors = $pal->Get_Color();
$colors_key = array_keys($colors);


    for($j=0;$j<$inc;$j++) {
        $out .= "";
    $out .= "";
    echo $out;

The above example is included in the download.

10 thoughts to “Generating a color palette from a image in php”

  1. Pingback:
  2. I have a very simple image consisting of a number of colored boxes bordered in black. It is actually a beading chart. Using Photoshop there are 4 colors used including the black for the borders. Once again using Photoshop (magic wand) I know the colors. I use this image for $image_to_read in your sample test. The result gives 6 colors and only one corresponds to the colors from Photoshop…. black. I am a little confused by this because I was hoping to use this method to create information for another program.

    Can you explain why I am seeing this difference? I used both gif and png.


    TTFN… Andrea

Comments are closed.