This tutorial will tell you how to write text to a blank dynamically generated PNG image in PHP. This is fairly simple, so it will just be the first step in a series of tutorials dealing with images in PHP. The image functions require the GD library to be installed.
The code we’re using and the output is below, and below that is an explanation of what the code does.
The first step is to tell PHP to create the image, we do this with the
imagecreate() function, which takes the desired width and height as parameters. This returns the image identifier, which we store in the variable
Next, we use the
imagecolorallocate() function to define some colours for use in our image. This takes as parameters, the image identifier we’re using, then the red, green and blue values for the colour. The first time we call
imagecolorallocate() it fills in the background of the image with that colour.
We then use the
imagestring() function to write text on the image. This function takes six parameters: the image identifier, an integer
5 determining which built in font to use (we’re choosing
y coordinates giving the top left position of the text, the text to write, and the colour to write it in.
It’s then time to output the image. First, we need to tell the browser what type of image we’re sending (this is normally text, which wouldn’t work for images), we do this with the line:
Next, we need to tell PHP to output the image as a PNG, this is done with the
imagepng() function, which takes the image identifier as a parameter.
That’s it! The last thing we do is to use the
imagedestroy() function to delete the image from memory, it takes the image identifier as a parameter.