Ooer.com by Chris Neale

Mondrian Art in PHP

Now that we have the positions for the blocks of colour in an array we can set about drawing the image. Initially we draw the black lines that make up the borders and segmentation in the picture.

<?php
for ($counter=0;$counter<$segments;$counter++) {
    if (
$block[$counter]['x']>0 or $block[$counter]['y']>0) {
        
imageline($canvas, 0, $block[$counter]['y'], 400, $block[$counter]['y'], $black);
        
imageline($canvas, 0, $block[$counter]['y']+$block[$counter]['h'], 400, $block[$counter]['y']+$block[$counter]['h'], $black);
        
imageline($canvas, $block[$counter]['x'], 0, $block[$counter]['x'], 400, $black);
        
imageline($canvas, $block[$counter]['x']+$block[$counter]['w'], 0, $block[$counter]['x']+$block[$counter]['w'], 400, $black);
    }
}
?>

The next stage in drawing the image is to fill in the colour blocks. To do this part we refer back to the array we generated at the beginning to define the locations and sizes of the blocks. There is a futher considereatin however. As we are using lines thicker than 1 pixel width we have to modify the blocks so that we don't overwrite what has already been drawn.

<?php
for ($counter=0;$counter<$segments;$counter++) {
    
imagefilledrectangle($canvas, $block[$counter]['x']+1, $block[$counter]['y']+1, $block[$counter]['x']+$block[$counter]['w']-2, $block[$counter]['y']+$block[$counter]['h']-2, $fill[rand(0,2)]);
}
?>

Actually filling the blocks is simply a matter of calling imagefilledrectangle(). The colour is defined using the array of colours we set up with at random integer between 0 and 2 as there are 3 possible colours. Adding more colours would simply be a matter of defining them in the initial array, and adding to the range of numbers the random function generates.

Finally we need to output the image.

<?php
header
("Content-Type: image/png");
imagepng($canvas);
?>

The header() function adds a content-type directive to the request from web browser telling it what to expect. In this case we're using a PNG image type, so we send the MIME type for PNG. Lastly we tell GD to convert our $canvas GD resource into PNG format and send it to the user's web browser.

Thats all there is to it. Building the image is quite an easy process, and it is quite effective too. With more time you could add to the code to improve things, but even at this early stage the results aren't at all bad.

To draw the image in a web page we need to use an IMG html element.

<img src="mondrian.php" width="400" height="400">

Each time the image is called it will generate a new artwork.

Move to page: 1 2 3

Comments

Comments are not currently being accepted for this article.
Sidebar
Published:
10/01/2007
Views:
9791
Author:
Chris Neale
Labels:
Print:
Sidebar: