Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 847
Gricey Avatar asked Mar 10 '12 05:03

Gricey


2 Answers

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

like image 190
mishu Avatar answered Oct 03 '22 15:10

mishu


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

like image 36
Jason Suárez Avatar answered Oct 03 '22 17:10

Jason Suárez