Random Mosaics with PHP


I've got a backlog of posts that I've been meaning to actually get online (I've got them in a big OneNote entry), but I usually like to annotate each post with some sort of header image. It just sort of looks better to have something there, in my opinion. Actually, I've been doing this for years and remember watching with amusement as the 'pro' blogs discovered the same thing and started putting any sort of random image they can find on each post (sometimes they're really annoying).

Anyways, I was thinking I should come up with a way of posting with auto-images so I didn't have to go find or make one and decided to whip up a quick PHP-based mosaic maker. Here's the code:

$w = 600;
$h = 300;

$s = rand(1,3) * 10;

$canvas = imagecreatetruecolor($w, $h);

for ($y=0; $y < $h/$s; $y++){
    for ($x=0; $x < $w/$s; $x++) {
        $color = imagecolorallocate($canvas, rand(0,255), rand(0,255), rand(0,255));
        imagefilledrectangle($canvas, $x * $s, $y * $s, ($x * $s)+$s, ($y*$s) + $s, $color);

header('Content-Type: image/png');


Nothing too exciting, but it makes a nicely random image each time it's called. I don't bother caching it - my blog doesn't get enough traffic to worry about it honestly, and the actual process isn't overly taxing on the server anyways. The PHP GD library is the same one I've used for auto-thumbnails and is pretty efficient - drawing a few random colored squares is nothing.

Hmm... let's see. If the image creates 10 pixel squares and is sized to be 600 x 300, that would be 60 x 30 or 1800 squares. Each of those squares can be any one of ~16M colors (256 x 256 x 256), which means that the mosaics can have 16,777,216 ^ 1,800 possible combinations (if I'm doing my math right, which I think I am...) equaling 3.131934594x1013004 possible mosaics.

So enjoy! The image above this post is unique not only for you, but most probably for all of time as well. (Do you feel special? You should!)



< Previous         Next >