| Downloaded from www.biorust.com on Thu Feb 09, 2012 12:10:31 |
![]() | |
| An Introduction to the GD Library Tutorial Author - Scrowler (http://forums.biorust.com/member.php?userid=66) |
Are you getting bored with standard PHP functions? Do
you want
to venture into additional libraries of PHP code? If so, GD is an additional module
that allows the programmer to develop graphics using PHP. Cool huh? You can do
things from drawing lines, to adjusting contrast, to anti-aliasing.
Before we start we need to make sure that your web server has GD enabled. To do this,
make a new file called phpinfo.php with the following string as its only
content:
<? phpinfo() ?>
This will output a big list of PHP settings, which is probably not very user
friendly. You are looking for a specific section - it will look something like
the following if GD is enabled on your server:

This is an example of the output of phpinfo() for a bundled GD distribution,
which is the common one, as it comes with newer versions of PHP. If you don’t
find this part in your phpinfo() output then you will need to find a
server that does support the libraries.
So, what are we going to learn in this tutorial? Let’s have a
look:
· Basic concepts
· Drawing lines
· Drawing polygons
· Drawing rectangles
· Drawing circles and ellipses
· Filling shapes
· Writing text on an image
· Outputting the image
That said, let’s get going! First of all, some basic concepts:
Basic
Concepts
The first thing you should learn about GDlib is its
capabilities. GD is a library of PHP functions that allows you to alter or create images
online. You can adjust the output quality, load files and alter them, or create
new images from scratch.
PHP images can be used just like any other image, i.e. you could use the
following HTML
to display a dynamic PHP image on a webpage:
<img src=”myscript.php” style=”width: 400px; height: 200px” alt=”My dynamic
PHP image” />
This is an example of valid XHTML syntax to display a dynamic image on a
webpage. Note that a lot of things are depreciated in XHTML, so you can’t use
attributes like height or width anymore, which is why I used a CSS-style definition instead. You can apply id’s or classes
if that is your fancy.
So, let’s start with some basic concepts. When you create an image from scratch,
you use the imagecreate() function to create a canvas. Its attributes are the
x
width and the y width. Here’s an example of the code for a 800x400px canvas:
|
<?php $x = 800; $y = 400; $im = imagecreate($x, $y); ?> |
You really need to get used to using image identifiers in GD, $im is the default variable
and is used a lot, although you don’t have to use if you don't like it for some
reason.
Next up, let’s learn how to allocate some colours, using imagecolorallocate().
With this, you can define colours for anything, and it is essential if you want
colours in your image.
This function accepts arguments 4 arguments: [image identifier], [R], [G], [B].
You put your image identifier variable in place, and numbers between 1 and 255
for each colour (red, green and blue). You can define as many different
variables as you like in different variables. Let’s have a look at an example I
prepared earlier:
|
<?php |
Coordinates are pretty easy to understand, using the
concept: x, y, the top left corner is 0, 0. So if we have a 150px square
image, the top right corner will be 150, 0, the bottom left will be 0,
150, and the bottom right will be 150, 150.
Outline functions (non fill functions) will by default draw a 1px
outline, and you can figure out for yourself how to make thicker lines... ;)
Finally, let’s find out how to load an image as opposed to creating a
canvas. There are special PHP functions to load images, and you can load
an image in the following main formats: .jpeg, .gif, .wbmp, and .png.
Instead of defining the image identifier with imagecreate() we simply
define it using one of the following functions:
· JPG/JPEG: imagecreatefromjpeg([filename])
· GIF: imagecreatefromgif([filename])
· BMP: imagecreatefromwbmp([filename])
· PNG: imagecreatefrompng([filename])
And that’s it! You can run a few protection procedures if you like, to
check whether the image was opened or not - all of these functions return
false if there was an error.
Right. That’s the basic principles of GD out of the way. You will
need to know how to output the image
once you’re finished, but that topic will be covered last.
Drawing Lines
At last, we’re finally getting into the art! Starting with
lines, let’s examine the function we will be using:
imageline ( [image] , [x1] , [y1] , [x2] , [y2] , [color] )
Our function imageline() accepts 6 arguments: the image identifier, the x
and y coordinates of the starting point for the line, the x and y coordinates
for the end point of the line and the colour identifier for the line (a variable
containing a call to imagecolorallocate() or similar).
You don’t call this function from within a variable, you simply call it, so
let’s try drawing a red line from 0,0 to 150,150 on an image:
|
<?php $im = imagecreate(150, 150); $bg = imagecolorallocate($im, 255, 255, 255); # let’s just use a white background. $red = imagecolorallocate($im, 255, 0, 0); # our red colour defined for the line imageline($im, 0, 0, 150, 150, $red); # output here, we will cover this later ?> |
And it’s done! Once the output functions have been put in, you will have a white 150px square image with a red line from the top left corner to the bottom right. It should look something like this:

Drawing Polygons
The functions for drawing shapes are essentially
simple to understand. The function we use to draw a polygon is called
imagepolygon(). It accepts 4 arguments: the image identifier, an array
containing each point’s x and y coordinate, the number of points in total and
the colour.
For the following example, I’ll make it easier by using the array function count() to
define the number of points for you, so all you will have to do is add new
points to the array. This example will create a 400x400px canvas and draw a triangle on it:
|
<?php $im = imagecreate(400, 400); $bg = imagecolorallocate($im, 0, 0, 0); # simple white background $red = imagecolorallocate($im, 255, 0, 0); $points = array( 200, 50, 50, 300, 350, 300 ); $num = count($points) / 2; # num now = 3 imagepolygon($im, $points, $num, $red); # triangle drawn # output image ?> |
And that's how we draw a triangle on a black canvas. After you have done this, and put in the outputting code, your image should look something like this:

A neat trick to try when using the imagepolygon() function is to define random points using mt_rand() instead of defining points. This can produce a cool effect, similar to this:

The above code is the same as the example above, except with the $points array
defined like this:
|
$points = array( mt_rand(50,350), mt_rand(10,80), mt_rand(10,100), mt_rand(200,390), mt_rand(250,390), mt_rand(200,390) ); |
You can put any point into the mt_rand() function,
but I put some coordinates that will limit the randomness to the general
area that I want the coordinate to make it look remotely like the
first example. Feel free to use this code in your work, I have used
random coordinates in imagepolygon() for a signature image or two... ;)
Now that's progression! Let’s go on to drawing rectangles (somewhat easier).
Drawing Rectangles
Now that we have read a bit about polygons, you
will whizz through this section. The GD function for drawing rectangles is,
funnily enough, called imagerectangle(). It accepts 6 arguments: the image
identifier, the top left x coordinate, and the y coordinate, and the bottom
right x coordinate, and the y coordinate, and the colour identifier.
imagerectangle() simply draws a rectangle from point [x1],[y1] to [x2],[y2]
using the specified colour and image identifier. Yep, that’s it! Let’s try:
|
<?php $im = imagecreate(400, 400); $bg = imagecolorallocate($im, 0, 0, 0); # simple black background $red = imagecolorallocate($im, 255, 0, 0); imagerectangle($im, 50,50, 350,200, $red); # rectangle drawn # output image ?> |
This script should output a black square, 400px wide and
high, with the outline of a rectangle from point 50,50 to point 350,200.
This only goes half way down the image simply to demonstrate that we don't
HAVE to draw squares.
Once completed, it should look something like this:

Drawing Circles & Ellipses
We can use the same methodology to draw
ellipses or circles. The function imageellipse() will do either, depending on
how we input arguments into it.
imageellipse() accepts 6 arguments: the image identifier, the centre point for
the circle [x], and [y], the width, the height, and the colour identifier.
When making circles, just pass the same variable in for the height as you do for
the width, so both will be the same. For ellipses, specify each separately, to
create the effect of a squashed circle.
Yep, GD functions are quite similar a lot of the time! Let’s try it:
|
<?php $im = imagecreate(400, 400); $bg = imagecolorallocate($im, 0, 0, 0); # let’s just use a black background. $red = imagecolorallocate($im, 255, 0, 0); # our red colour defined for the circle $white = imagecolorallocate($im, 255, 255, 255); # white for the ellipse $circle = 200; $ellipse["w"] = 300; $ellipse["h"] = 100; imageellipse($im, 200, 200, $circle, $circle, $red); # our circle is drawn in the middle imageellipse($im, 200, 200, $ellipse["w"], $ellipse["h"], $white); # our ellipse is drawn over the top # output here, we will cover this later ?> |
You don’t have to define the ellipse width and height in an array, but I thought I may as well because I am exampling a circle and an ellipse in the same script. This should draw the outline of a red circle in the middle, and the outline of a white “squashed circle” – ellipse over the top. It should look like this:

Filling Shapes
This is not as hard as it may sound. In fact, it’s
merely a change of function names! You simply add the word “filled” into the
name of the function and it gets done! The arguments are the same as the outline
functions, so that’s not a problem. Here’s a couple of examples:
· imagepolygon() => imagefilledpolygon()
· imagerectangle() => imagefilledrectangle()
· imageellipse() => imagefilledellipse()
Etc... And that’s it! That’s all you need to do to fill a shape! Instead of
drawing an outline with [color], it will fill the shape outline with [color]!
Here’s a couple of examples from previous sections, using filled functions this
time:
![]() |
![]() |
![]() |
Writing Text Onto An Image
Writing text is just as simple as using the
shape functions - it uses an image identifier, and a colour identifier. It also
uses an x and y coordinate to define where to start writing.
imagestring() accepts these arguments: image identifier, font, [x], [y],
string, colour
The font argument basically represents the font size, you can change the font
using some other GD functions like imageloadfont() which I wont go over
in this tutorial.
So let’s give it a go. Let’s make a canvas, and output some text onto it!
|
<?php $im = imagecreate(800, 400); $words = "imagestring ex. by scrowler"; $bg = imagecolorallocate($im , 0,0,0); $txt = imagecolorallocate($im , 255,255,255); imagestring($im, 2, 200, 300, $words , $txt); # outputting ?> |
That’s it! You can extend yourself by giving the user a form
to input data, you can load up an image first, then put inputted text on it.
You can even apply wordwrap() formatting to define an edge to where
text can go!
Now… After all that time, let’s finally get on to outputting the image!
Outputting The Image
Like the other functions, outputting images is a
real doddle! The first step is to decide which major format you wish to
output to: .jpg, .gif, .bmp or .png.
Now set the header content to that image type (you can use a form, as $_FILES[‘file’][‘type’]
will return the appropriate format for this, but let’s do it manually):
· JPG/JPEG: header(“Content-type: image/jpeg”);
· GIF: header(“Content-type: image/gif”);
· BMP: header(“Content-type: image/wbmp”);
· PNG: header(“Content-type: image/png”);
Right, after we’ve done all that, there’s only one more important step: actually
outputting it. We’ve now told the browser that this is an image, so let’s output
the content. To do this, we use image[type](). This function accepts
these arguments: image identifier, filename, quality.
Substitute the [type] in the above function to .jpeg, .gif, .png or .wbmp to
output to different formats. The image identifier argument is the variable name
containing all the image data you’ve processed through the script. The filename
specifies where you want to save the image, but we aren’t saving it, so just put
"" in there. The last argument sets the quality - this is a simple
integer from 1 to 100 specifying the output quality of the final image.
And you’re done! Have fun, here’s a couple of examples:
|
<?php # jpeg header(“Content-type: image/jpeg”); imagejpeg($im, “”, 100); # png header(“Contept-type: image/png”); imagepng($im, “”, 100); # etc… ?> |
If you have any problems, comments or suggestions for this
tutorial, don’t hesitate to contact me via the
BioRUST Creative Forums. You can
click my name below to visit my profile, where you can email or send a
private message. I will be happy to help you. I hope I have inspired you to
create a new kind of art. Goodbye and good luck!
PS. You can download the example files by clicking
here. ;)