0

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?

4
  • After 15 pixels successfully randomized, the script stops? without an error? Commented Sep 10, 2013 at 9:11
  • i know its no error but i need random color for each pixel for all 12X120 pixel Commented Sep 10, 2013 at 9:16
  • Each time i run your script. I get different colors. What do you expect to print ? Commented Sep 10, 2013 at 9:18
  • im35.gulfup.com/4At9d.png that what i get when i run code Commented Sep 10, 2013 at 9:23

1 Answer 1

2

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));
        }
    }
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.