Liam Delahunty: Home Tips Web Contact
Recommended laptop
under £500
.

Think I deserve a present? See my Amazon Wish List

PHP Randomised Image Generator

See the demonstration over at PHP Random Coloured Lines V.1 and PHP Random Coloured Lines V.2 the only difference between the two is the "COLOR_DEVIATION" value. Refresh the page for a new image.

I'm not sure exactly where I got the base code from, my thanks go to the original author, I think it may have been via PHP4 Multimedia Programming published by Wrok.


//seed random generator
srand((double)microtime()*1000000);

define("IMAGE_WIDTH",715);
define("IMAGE_HEIGHT",300);
define("MAX_LINE_WIDTH",10);
define("COLOR_DEVIATION",18);

// create an image resource
$img = imagecreate(IMAGE_WIDTH,IMAGE_HEIGHT);

// start at middle grey...
$lr = $lg = $lb = 127;

function cmax($x) {
// make sure our color value is a sane number
if ($x > 255) { return 255; }
elseif ($x < 0) { return 0; }
else { return $x; } }

function ncolor($x) {
return rand($x - COLOR_DEVIATION, $x + COLOR_DEVIATION); }

// draw vertical fills
while($p < IMAGE_WIDTH) {
$linecolor = imagecolorallocate($img,
$cr = cmax(ncolor($lr)),
$cg = cmax(ncolor($lg)),
$cb = cmax(ncolor($lb)));
$linewidth = rand(1,MAX_LINE_WIDTH);
imagefilledrectangle($img,$p,0,$p+$linewidth,IMAGE_HEIGHT,$linecolor);
$p = $p + $linewidth;
$lr = $cr;
$lg = $cg;
$lb = $cb;
}

// return the image to the client
header("Content-type:image/png");
imagepng($img);

Share this!