Gricey
Gricey

Reputation: 1441

How to generate a completely random image?

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

Upvotes: 9

Views: 6828

Answers (3)

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

Upvotes: 0

Jason Su&#225;rez
Jason Su&#225;rez

Reputation: 2555

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

Upvotes: 3

mishu
mishu

Reputation: 5397

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

Upvotes: 7

Related Questions