7

I'm trying to generate a completely random image of a given size.

Here is what I have so far:

<?php
$Width = 64;
$Height = 32;

$Image = imagecreate($Width, $Height);
for($Row = 1; $Row <= $Height; $Row++) {
    for($Column = 1; $Column <= $Width; $Column++) {
        $Red = mt_rand(0,255);
        $Green = mt_rand(0,255);
        $Blue = mt_rand(0,255);
        $Colour = imagecolorallocate ($Image, $Red , $Green, $Blue);
        imagesetpixel($Image,$Column - 1 , $Row - 1, $Colour);
    }
}

header('Content-type: image/png');
imagepng($Image);
?>

The problem is that after 4 rows it stops being random and fills with a solid colour like this
Sample of problem

Gricey
  • 1,321
  • 1
  • 18
  • 38
  • 4
    Use `imagesetpixel()` instead of the filled rectangle. far less overhead to set a single pixel than do a 1x1 rectangle. – Marc B Mar 10 '12 at 05:16
  • @MarcB Thanks for that tip, has made it faster but it still suffers from the same problem – Gricey Mar 10 '12 at 05:18
  • 2
    4x64 = 256, which is the limit for an 8bit image (since you're not using imagecreateTRUECOLOR()) is all you can have. – Marc B Mar 10 '12 at 05:23
  • Ah, that was the finer point that I was missing. Thanks for the help – Gricey Mar 10 '12 at 05:24
  • 2
    @MitchellGrice, I'm surprised you could be bothered to try posting again. Your last comment, "I don't want to spend hours learning all about the PHP image library and how it handles colours for something as trivial as this", (http://stackoverflow.com/questions/9643978/how-to-generate-a-completely-random-image), definitely left me not in the mood to help with your questions. I'm happy others have, but the whole point of this site is to learn. If you aren't interested in that, don't bother asking questions. In any case, thank you for adding some code to your post this time around. – Brad Mar 10 '12 at 05:26

3 Answers3

7

if you change imagecreate to imagecreatetruecolor it should work (everything else is the same, including the parameters)

mishu
  • 5,347
  • 1
  • 21
  • 39
3

By allocating a new color for each pixel, you are quickly exhausting the color palate. 4 rows at 64 pixels per row is 256. After the palate is full, any new color will use the last color on the palate.

Mishu's answer uses a full-color image, rather than and indexed color image, which is why you are able to allocate more colors.

See this answer in the PHP docs http://us.php.net/manual/en/function.imagecolorallocate.php#94785

Jason Suárez
  • 2,445
  • 3
  • 18
  • 20
0

Both create images with different palletes. True color has more color ranges so its better to use imagecreatetruecolor()