Ooer.com by Chris Neale

Starting Out with GD

The next step is to draw a border around our image. This is achieved by drawing an unfilled rectangle slightly within the confines of the image. The function to draw an unfilled rectangle is imagerectangle().

<?php
imagerectangle
($image,0,0,199,199,$black);
?>

By now our image should be a white square with a single pixel white border around the outside.


The next thing to do is to add an image to the middle. We'll be copying from another image.

<?php
$girl
= imagecreatefrompng("girl.png");
?>

Now that we have our image that we wish to copy from we need to now how large it is in order to copy it. Using the functions imagesx() and imagesy() we can find this out very easily. We also need to calculate where in our image we wish to place the copied image data.

In our final image we need the picture of the girl to be placed centrally, but with enough space to place a caption below it, so we will simply place the image 15 pixels down on our final image.

<?php
$x
= imagesx($girl);
$y = imagesy($girl);
$px = ((200-$x)/2);
$py = 15;
?>

The next stage is to copy the data from the image of the girl to our image. To do this we need to use the imagecopy() function. It is rather more complicated than previous image commands as there is a long list of variables that are required.

<?php
imagecopy
($image,$girl,$px,$py,0,0,$x,$y);
?>

This copies to $image, from $girl, to the coordinates that we calculated in step 9. We are copying from position 0,0 in our picture of a girl, and taking the full dimensions of the gir image that were placed into $x and $y in step 9.

Finally we need to add a caption to our picture. There are many ways to add text to an image using GD depending on which libraries are complied into your version of PHP. To keep things simple however we will stick with the built in text creation tools.

The function imagestring() is what we use to write text onto images. imagestring() gives access to 6 built in fonts, each varying in size and weight. Normal text is font number 4, but as the built in fonts start from 0 it is numbered 3. To calculate the width of the text we will be placing on our image we need to know the width of each letter in the font. This is found using the imagefontwidth() function. We then multiply that with the number of letters in our caption string.
Move to page: 1 2 3

Comments

Comments are not currently being accepted for this article.
Sidebar
Published:
17/01/2007
Views:
2658
Author:
Chris Neale
Labels:
Print: