Creating images on the fly can be a very useful skill. PHP has some built-in image generation functions, further more, to generate new images or edit existing images on the fly using PHP, we need to have the GD library installed. In this tutorial we will show you how to get quite interesting and useful effects using image handling functions. We will review two practical tasks: creating security images (captcha) on the fly and building a bar chart using numerical values retrieved from MySQL database.
Creating security images on the fly
At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.
To create a new image or edit an existing one, we need to create image identifier. In the preceding example we created an empty canvas by calling ImageCreate() function, passing it width and height of a new image as a parameters. Another way to do it is to read the existing image from the file. Depending on the file format you can do it using one of the following functions: ImageCreateFromPNG(), ImageCreateFromGIF(), ImageCreateFromJPEG(). Parameter of each function is a file name.
Then, we need to choose colors to be used while painting. For this we can use ImageColorAllocate() function and image identifiers for red, green, and blue (RGB) components of necessary color will be passed as parameters.
On the next step, we will generate our image. First, using ImageFill() function we will create black background. Parameters of this function are: image identifier, initial coordinates of the area to be filled and fill color. Then, we will use ImageString() function to add text to the image. Its parameters are – image identifier, font, coordinates for the first text position and text color. Finally, we will draw two lines and a rectangular to protect our image a little bit. Please note, that the final point of the rectangular has the following coordinates: $width-1 and $height-1. If they were equal to $width and $height, than the rectangular would have exceeded canvas frame.
When we had created the image, we can output it either to a browser, or to a file. Our example shows how to output it to the browser. We need to inform the browser, that we will output the image, not the text or html-code. To do it, call Header() function, setting image MIME-type. It’s worth mentioning that Header() function can not be executed if HTTP header has already been sent. After sending the header we can output our image using ImageJpeg() function, passing it image identifier as a parameter.
When we have finished working with the image we need to free up resources using ImageDestroy() function.