Reputation: 27
i am trying to create image with PHP and GD library
when i wrote this code no error found
<?php
header("Content-Type: image/png");
$im = @imagecreate(120,120) or die("Cannot Initialize new GD image stream");
for ($i =0; $i<120; $i++) {
for ($j = 0; $j<120; $j++) {
$color = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im, $i,$j,$color);
}
}
imagepng($im);
imagedestroy($im2);
?>
but i need to set random color for each different pixel ,but i dont know why loop stop in 15 when i set width and height for 120px
what is the problem?
Upvotes: 0
Views: 271
Reputation: 85598
This is because at some point imagecolorallocate
will return false or another negative value.
http://www.php.net/manual/en/function.imagecolorallocate.php
Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
You actually try to create the same color for the image over and over again. So simply consider that you may already have allocated / created the random color in your loop :
for ($i=0; $i<120; $i++) {
for ($j = 0; $j<120; $j++) {
$color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
if ($color) {
imagesetpixel($im, $i, $j, $color);
} else {
imagesetpixel($im, $i, $j, rand(0, 255));
}
}
}
Upvotes: 2