Arno Nymo Arno Nymo - 3 months ago 7
PHP Question

Phpimagesetpixel not working

I am trying to generate images with gardients. But the generator stops after the first row of the image and only outputs black from there on.

My code:

<?php
$my_img = imagecreate( 255, 255 );

for($y = 0; $y < 255; ++$y){

for($x = 0; $x < 255; ++$x){

$color = imagecolorallocate($my_img, $y, $x, 0);
imagesetpixel($my_img, $x, $y, $color);

}

}

header( "Content-type: image/png" );
imagepng( $my_img );
?>


What can I do to make it continue generating?
Thanks in advance.

Answer

You ran out of colors.

Quoted from a user comment on the documentation of imagecolorallocate:

Note that you can only assign 255 colors to any image palette. If you try assigning more, imagecolorallocate() will fail.

In fact, the maximum is 256. As you created the maximum number of colors already after the first line (which has 256 colors, including black as the first one), the rest of the imagecolorallocate() calls give false, which corresponds to a integer value of 0, and gives every other pixel the color black -- the first one you created.

Here is code that would work, generating only 256 pixels:

$my_img = imagecreate( 16, 16);

for($y = 0; $y < 16; ++$y){
    for($x = 0; $x < 16; ++$x){
        $color = imagecolorallocate($my_img, $y*16, $x*16, 0);
        imagesetpixel($my_img, $x, $y, $color);
    }
}

header( "Content-type: image/png" );
imagepng( $my_img );

For creating images with true colors (more than 256), create the image with imagecreatetruecolor. With that change your code will produce the expected result:

$my_img = imagecreatetruecolor(256, 256);

for($y = 0; $y < 255; ++$y){    
    for($x = 0; $x < 255; ++$x){    
        $color = imagecolorallocate($my_img, $y, $x, 0);
        imagesetpixel($my_img, $x, $y, $color);    
    }    
}

header( "Content-type: image/png" );
imagepng( $my_img );