PHP makes it very easy to do many things needed on a website, among which is to create an image. The ability to generate an image in PHP can be useful if you want to do things like create CAPTCHA images, or even design a banner or logo on the fly the way some free blogging software do.
By the end of this tutorial, you will be able to create or modify an existing image using PHP, set the colours ("colors" in US English) of its background, the text and the lines you draw, write text to that image, draw a line and set its thickness. You will also be able to either send that image to a web browser or to save it as a file. Armed with this basic foundation, you will also be able to knowledgeably explore further and perform more complex operations on images using PHP if you wish.
Note: If you are here looking for an article on how to create banners or logos for your website, and not strictly for an article on how to write PHP scripts to generate such images, you may find my article on How to Create a Logo for Your Site the Quick and Easy Way more relevant.
I will assume that you already have some basic knowledge of how to write PHP programs. If not, you may wish to check out my basic PHP tutorial, How to Program in PHP.
For any of the functions listed here to be available, your PHP interpreter must have been compiled with the GD library. If you are using the PHP provided by a commercial web host, this is probably already provided as a standard feature.
If you want TrueType font support, your PHP must have FreeType support compiled into it as well.
The easiest way to understand how to create an image is by looking at some sample code.
The above code creates a 200x80 PNG image with a blue background and yellow text. It can be called from within your web page
simply by referencing the php file. For example, if the PHP file that contains the above code is called
myimage.php, then the
HTML code to invoke it can simply be:
The first thing the code does is to call the
imagecreate() function with the dimensions of the image, namely its
width and height in that order. This function returns a resource identifier for the image which we save in
The identifier is needed for all our operations on the image.
If the function fails for some reason, it will return FALSE. If you want your code to be robust, you should test for this. The demo code above doesn't do any error checking, since it will clutter the example, making it harder to understand.
Before you can use any sort of colours in your image at all, you will need to allocate them. Colours are represented by three digits, known as the RGB value. The first digit denotes the red component, the second the green and the third blue, hence RGB, for Red-Green-Blue. These are the same colour values that you use for your web page as well as numerous other computer applications.
Colours are allocated using the
imagecolorallocate() function. This function will automatically fill the background
of the image with the colour the first time you call it, as well as return an identifier for that particular
colour. Subsequent calls to
imagecolorallocate() will simply create a colour identifier for your colour, without
affecting your image background.
As you can see from the above code, my script allocates a blue identifier for the image, and in so doing, causes
imagecolorallocate() to set the background to blue automatically. It also allocates a colour identifier for yellow and
one for a shade of green. The latter two identifiers will be used later to write text and draw a line.
imagecolorallocate() returns FALSE if the function fails for any reason.
To write text to your image, you will need to use the
imagestring() function. This function uses a set of built-in
fonts to do the writing. The fonts have various sizes, ranging from 1 to 5, where 1 is the smallest font size and 5 the largest.
The size of the font is specified in the second parameter to the function. In my example, I used font size 4.
The third and fourth parameters to
imagestring() specify the x,y coordinate for the top left hand corner of the text. In the
case of the example above, my text will begin 25 pixels from the top edge of the image, and 30 pixels from the left.
The fifth parameter is for the text to print, and the final parameter the colour of the text. This is the same colour that
was allocated earlier using
imageline() function can be used to draw a line to the image. To set the thickness of the brush used to draw
the line, you may want to call the
imagesetthickness() function as I did in my example. The numeric parameter to
imagesetthickness() is the thickness of the brush in pixels. In my code, I set it to 5 pixels.
If you don't call
imagesetthickness(), the line will be 1 pixel thick.
imageline() function is called with the start and end coordinates of the line, in x,y format. In my code,
the line starts from 30,45 and ends on 165,45. That is, it will be a horizontal line 45 pixels from the top, starting 30 pixels
from the left edge and ending 165 pixels from that same edge. Since
$line_colour was set to a shade of green earlier,
the line will be green.
Since the output of my example script is the image itself, I send an "image/png" content type header to the
browser telling it that what follows are the bytes of a PNG image. The function
imagepng() is then called to
generate the necessary image from my
$my_img image identifer. Since I called
a second parameter, the function automatically sends its output to the browser. If you prefer to save your image, don't call the
header() function to output the header, and call
imagepng() with the filename of the image for its
second parameter, like the following:
Your image does not have to be a PNG image. You can use
imagejpeg() to create GIF and JPG
images respectively. You should of course send the correct content type header for the type of image you are creating. For example,
a jpeg image should have a content type of "image/jpeg" while a gif image "image/gif". Note though that GIF support may or may not
necessarily be compiled into the version of the GD library your web host is using, so if you're not sure, use one of the other file formats.
On completion, the program releases the resources associated with the image by calling
imagedestroy(). I'm not sure if any of these calls are really necessary
if your script is going to terminate immediately, since I don't know if PHP automatically cleans up all these resources on
the termination of the script. I like to put those calls there for completeness.
In most cases, creating an image from scratch is overkill. For most web purposes, you can usually design the basic background of your image using a normal image editor and only add any additional text or graphical elements that need to be dynamically drawn using PHP. This allows you to speed up your scripts and reduce the resource consumption on your web server. It also lets you create your picture using professional picture designing tools.
To use an existing GIF, JPEG or PNG image as a canvas on which you add additional elements, use one of the following functions instead
imagecreatefromgif ( string $filename )
imagecreatefromjpeg ( string $filename )
imagecreatefrompng ( string $filename )
For example, if you created a GIF file called "mytemplate.gif", the function can be called as follows:
Like the basic
imagecreate() function, these functions return FALSE if they fail to load the image for any reason.
If you want to use a True Type font, you will need to use
imagettftext() instead. For
details on how to use this function, please consult the function's manual page on php.net.
You should note a few things, though, before using this function:
Check that your web host has compiled FreeType support into PHP before you rely on this function.
Find out whether your web host's PHP is using GD version 1 or 2. This affects a number of things, including the meaning of the font size parameter to the function (whether it means pixel size or point size).
Note that the coordinates for the text has a different starting point from
imagestring(). That is, a coordinate like
(say) 10,20 has a different meaning in the two functions.
Make sure the font you want exists on your web server. Remember that your web server is not the same as your computer. Just because a font like Arial exists on your computer does not mean that it exists on your server. If you have fonts that you created yourself, you may want to upload those to your web directory and use those instead. At least, that way, you have a guarantee that the font needed by your script exists.
The path setting to the font file is tricky, and depends on the version of the GD library your web server is using. One way around it is to specify the full path to the file on your server.
Besides the line drawing function used above, PHP has other functions that you can use. A complete list of functions, along with their descriptions, can be found on http://www.php.net/gd. To whet your appetite, functions include those that allow you to draw ellipses, arcs and polygons, change the style of your lines (to say dashed lines), and so on.
However, unless you have special reasons why you might want to dynamically draw complex pictures onto an image, you should
consider creating your base image using a normal picture editor,
load that image using a function like
imagecreatefrompng(), and then only modifying small details with your script. Generating everything from
scratch is unnecessary for most purposes, and can
drain your web server resources.
Congratulations. You can now write scripts that create and output images, write text to those images, set the brush thickness for lines and draw those lines. You also have enough basic knowledge to intelligently explore further the other facilities available in PHP to design and modify your images.
Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.
It will appear on your page as: