Creating new images

resource imagecreate ( int x_size, int y_size)

int imagedestroy ( resource image)

int imagecolorallocate ( resource image, int red, int green, int blue)

It's time to go from theory to practice and get stuck in with image creation! Here is what we've got so far:

<?php
    $image = imagecreate(400,300);
    // do stuff to the image
    imagejpeg($image, '', 75);
    imagedestroy($image);
?>

Go ahead and save that in your public HTML directory as picture1.php. As most of your pictures will probably be referenced from a web page, we will also make a companion web page. Save this as phppicture.html:

<html>
<title>PHP Art</title>
<body>
PHP woz 'ere:
<img src="picture1.php" />
</body>
</html>

That is all you need to get started - open up your web browser and load in phppicture.html - you should see a large black box for the image.

Author's Note: Be sure not to have anything outside the PHP code block, not even an empty line. Everything outside the PHP block is sent to the browser as part of the picture, and even having a single space character at the end of the file will cause problems.

The next step is to add a little colour in place of the "do stuff to the image" comment, and for this task we will enlist the help of imagecolorallocate(). This new function takes four parameters - the image resource you are choosing a colour for, then three integers between 0 and 255, one each for the red value, then green value, and the blue value of the colour. You can also specify these colours in hexadecimal format (e.g. 0xff) rather than decimal.

The first colour you allocate is automatically used as the background colour for your image, so this next piece of code is a minor modification of the last script to include colour information...

<?php
    $image = imagecreate(400,300);
    $gold = imagecolorallocate($image, 255, 240, 00);
    imagepng($image);
    imagedestroy($image);
?>

Save that over picture1.php, and refresh phppicture.html - you should see the black square turn replaced by a yellow square. Not a big step forward, but a step forward nonetheless!

Author's Note: Don't worry about deallocating colours, as they are just numbers and not resources, meaning they don't use up any special memory. If you really want to deallocate a colour (perhaps if you're working with a paletted image), use the imagecolordeallocate() function.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Choosing a format >>

Previous chapter: Images

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.