Imagecopy with PHP and GD
Lesson 5: Drawing on image with GD

The GD Library which is bundled with PHP has built in functions which allow you to draw on your image, or draw an image on a blank page. This lesson uses some of these functions to draw a face on a cat which was created with imagecopy. I am not going to cover all the imagecopy codes in this lesson as they should be evident from the previous lessons. Here is the final version of the image after it has been made into a jpg and resized.

cat

The face was drawn with GD. For more information on all of the GD functions available, Sally has a number of tutes that can take you through it step by step at SimplySally.com

To briefly run down the codes used, first I drew oval shaped circles for the eyes. Then I drew arcs for the mouth and finally lines for the nose.

The first thing you need to do is allocate the color you want to use. Name the color in a variable and then assign the decimal or hexidecimal codes as follows:

$black = imagecolorallocate($im, 0, 0, 0);
OR
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

Once you have assigned the colors you need to use, then you can start drawing with these colors.

For an ellipse you need to define the center of the circle (width and height as it will appear on the background), and then the width and height of the circle, regardless of the background==just the size of the circle. The code may look like this:

imagefilledellipse($im, 100, 150, 30, 30, $black);
Or just an outline of a circle:
imageellipse($im, 100, 150, 30, 30, $black);

An arc can be used to draw a semicircle. Again Sally has a nice tutorial on drawing arcs. It is similar to an ellipse except it has two more parameters that define the angle of the arc as points around a circle from 0-360 degrees. The code appears like this:

imagearc($im, 100, 150, 30, 30, 0, 180, $black);

Finally I have used lines to draw the nose. A line needs a start point on the background, x, y, and an end point, x, y, and the color. The code will look like this:

imageline($im, 100, 150, 125, 150, $black);

OK, here is the php image and a close up of the face so you can see what was drawn. Look at the codes and see how they work.



CODES

ZIP THIS LESSON