PHP code to get the most common colour in a block

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm trying to write some code that will read in an image and, after
making the width and height the same, chop it into smaller squares and
make another image based on the most common color in each square.
However, I have run into a problem with a call to php's
function, where I am told that the Color index is out of range. Can
some kind soul please suggest a solution? I think the problem lies in
the palette of the image but I can't see what.

The code I am writing is:




$imgname="C:\Documents and Settings\Paul\test.PNG";

    list($width, $height, $type, $attr) = getimagesize( $imgname );

// Now find out which of these is bigger - width or height
// make $imgresized a square equal to the bigger of these two

$dimension = $height > $width ? $height : $width;

$imgresized = imagecreate( $dimension , $dimension );

$black=Imagecolorallocate($imgresized, 0,0,0);
$white=Imagecolorallocate($imgresized, 0xFF,0xFF,0xFF);

// This is the image that will be analysed, chunk by chunk

        // 1 = GIF, 2 = JPG, 3 = PNG

        switch( $type )
            case 1:
                // Load $foregroundimagefilename, convert and save
                $tempimage = imagecreatefromgif( $imgname );
                imagepng($tempimage, "foreground.PNG");
                $origimg = imagecreatefrompng('foreground.PNG');
                imagecopy($imgresized, $origimg, 0,0,0,0,$width, $height);
            case 2:
                // Load $foregroundimagefilename, convert and save
                $tempimage = imagecreatefromjpeg( $imgname );
                imagepng($tempimage, "foreground.PNG");
                $origimg = imagecreatefrompng('foreground.PNG');
                imagecopy($imgresized, $origimg, 0,0,0,0,$width, $height);
            case 3:
                rename( $imgname, "foreground.PNG" );
                $origimg = imagecreatefrompng('foreground.PNG');
                imagecopy($imgresized, $origimg, 0,0,0,0,$width, $height);
                die("Could not process your file");

// Create image to display to the user.
$img = imagecreate( 2*$offset+$max_dim*$distance, 2*$offset+$max_dim*
$distance );

$white2=Imagecolorallocate($img, 0xFF,0xFF,0xFF);

$black2=Imagecolorallocate($img, 0,0,0);

// Set background colour to white
$ret_val = ImageFilledRectangle($img,0,0,2*$offset+$max_dim*$distance,

for($row=0; $row<$max_dim; $row++)
    for($col=0; $col<$max_dim; $col++)
        // Chop original image into chunks, of size (width/max_dim) and
        //get image details from col to col+1 and row to row+1
        // int imagecolorat  ( resource $image  , int $x  , int $y  )

        if($col<$max_dim-1 && $row<$max_dim-1)

            $colourfound = commoncolour($imgresized, $row, $col, $max_dim);

            //transform $colourfound (int) to $foundcolour (hex)

            $rgb = imagecolorsforindex($imgresized, $colourfound);

            $colorcalc = imagecolorallocate( $img, $rgb["red"], $rgb["green"],
$rgb["blue"] );

            imagefilledrectangle($img, ($offset+$col*$distance),
             ($offset+$row*$distance), ($offset+($col+1)*$distance),
             ($offset+($row+1)*$distance), $colourfound);


        imagerectangle($img, ($offset+$col*$distance),
         ($offset+$row*$distance), ($offset+($col+1)*$distance),
         ($offset+($row+1)*$distance), $black2);


header('Content-Type: image/png');

function commoncolour($img, $row, $col, $max_dim)
// $row goes from 0 to $max_dim-1 ---> location is ($row)/($max_dim-1)
to $row+1/($max_dim-1)
// this scales to round($height*(....))

    $colourlist = array();
    $dimension = imagesx( $img);

    for($irow=floor(($row*$dimension/($max_dim-1))); $irow<floor((($row
+1)*$dimension/($max_dim-1))); $irow++)

        for($icol=floor(($col*$dimension/($max_dim-1))); $icol<floor((($col


            $colourval = imagecolorat ($img, $icol, $irow );
            // Now add $colourval to an array

            // We now create a hash table for the found colours, so that we can
            // a colour value with how many times it has been found so we can
get the most common
            // colour.

            if (!array_key_exists($colourval, $colourlist))
            // if it already exists, increment counter
            // when finished sort values


            // return most common colour; the last item in the list

            $colfound= array_pop($colourlist);

            return $colfound;




Re: PHP code to get the most common colour in a block wrote:
Quoted text here. Click to load it

This sounds like you are trying to write your own version of imagecopyresampled:

Quoted text here. Click to load it

Try imagecolorat:

Site Timeline