Introduction
Have you ever wondered how some e-greeting websites put your text in the card image? Or perhaps you've noticed an image in somebody's forum signature that showed your IP? This article will show you this is done using a few practical examples.
A dynamic image can be a very powerful and informative tool, and in this article I will discuss the basics of creating generating on-the-fly images with PHP and the GD library (http://www.boutell.com/gd/).
This article assumes that your host has both PHP and the GD library installs and will not cover the installation procedure(s).
Your First Image
Let's start by creating and outputting a very simple image.
<?php Header( "Content-type: image/png"); $image = imagecreate(320,130); $red = ImageColorAllocate($image,204,0,0); ImageFilledRectangle($image,0,0,320,130,$red); ImagePNG($image); ImageDestroy($image); ?> |
Let's go by this line by line.
Header( "Content-type: image/png");
First, we override the default HTTP header with a "Content-type: image/png" header. Basically, this is telling the browser to interpret the following as an image, because that's what it is.
$image = imagecreate(320,130);
Next, we must assign a variable to our image (in this case, $image). In english, the line would state "Create an image 320 by 130 pixels and put it into memory as $image.
$red = ImageColorAllocate($image,204,0,0);
All colours that you use must be allocated, this is done via the ImageColorAllocate() function. In this example, we set $red to 204,0,0 RGB.
ImageFilledRectangle($image,0,0,320,130,$red);
Here's when we actually draw the red rectangle using the ImageFilledRectangle() function. We're telling GD to create a rectangle in $image, starting from top-left (0,0), make it 320x130 pixels and colour it red.
ImagePNG($image);
Up to this point, the image has been stored in memory. This is when PHP will actually output the image to the browser - this is done using ImagePNG(), because in our case we are creating a PNG image.
ImageDestroy($image);
Finally, the image should be destroyed from memory since it has been outputted to the client.
You can now call this script from the browser directly (www.yourdomain.com/createpng.php) or using the <img> tag, IE: <img src="createpng.php>.
Head over to the next page where we deal with dynamic data, and outputting text on to our image!