Coding tutorials

Center align text with GD - PHP

Written by Python - Monday 5th of May 2008

Total views: 3840
Unique views: 1990

Add to favourites

Advertise here Advertise here

Adding text to an image is one thing but getting it to align in the center of your image is a little trickier when it comes to PHP. This tutorial will show you how it's done with the use of the very powerful and widespread GD library. If your host does not have the GD library or if you are unsure if you have access to it I recommend that you contact your host's support and see what they can do.

Table of contents

  1. Introduction to GD
  2. Getting started
  3. Adding some text
  4. Making it align center

1. Introduction to GD

The GD image library is one of the most common PHP modules used in order to create and manipulate images. It is a very powerful library with a whole load of functionality which when used correctly can produce some brilliant results.

In this particular tutorial we will make use of a number of the capabilities of the GD library to get the desired result.

2. Getting started

So then, lets begin.

Take a look at the following PHP code snippet. It contains a typical, minimal setup for using some of the most basic functionality built into GD.

// Some basic setup
$imageWith = 300;
$imageHeight = 200;

// Set the headers content type
header("Content-type: image/png");

// Create the image
$image = imagecreatetruecolor($imageWidth, $imageHeight);

// Create some colors
$black = imagecolorallocate($image, 0, 0, 0);

// Fill the background of our image
imagefilledrectangle($image, 0, 0, $imageWidth, $imageHeight, $black);

// Output the image to the browser
imagepng($image);

// Destroy the image
imagedestroy($image);

So what exactly will this do? Well to be honest not all that much. To begin with at the top of the snippet we have defined two variables, $imageWidth and $imageHeight. These of course contain the width and height of the image we want to create in pixels (in this example 300 by 200).

We then, using the
header() function set the pages Mime-type to be "image/png". Doing this means that when a web browser visits our script it will treat it as an image file (.PNG) instead of a HTML web page.

The next part is where we first make use of the GD library. By using the imagecreatetruecolor() function and assigning its result to the variable $image we are able to create our plain canvas on which we can build our images content. This function takes two paramaters which are the width and height of the image we wish to create.

Now that we have created our canvas to work with we can now start to think about colours. For this simple example the only colour we need to consider is the background colour. To create and assign a colour to a variable for later use we use the imagecolorallocate() function. This function takes four parameters which is the blank image we created earlier ($image), and then three values to represent a particular colour in RGB. In this example above the RGB 000 creates the colour black.

Once we have our background colour ready we can then go ahead and apply it to the whole of our image. To do this we use the imagefilledrectangle() function which creates a rectangle and fills it in with the given colour. This function takes 6 parameters which are our original image ($image), 4 co-ordinates (the start and end points of the rectangle) and the colour we want to use ($black).

Our images background colour has now been made black. Although it's not a very exciting or useful image now might be a good time to output it to the browser. To do this we use the imagepng() function which takes at least one parameter (up to 4). For this particular example we only need to worry about the first parameter which is the image we have been working with ($image).

The final line of code above is the imagedestroy() function. So far everything which we have been doing with our image has been stored on the server in a temporary location and this should ideally be cleared. Similar to the imagepng() function this function only requires one parameter which is our image ($image).

The result of this script is this.

3. Adding some text

Now that we have covered the basics of GD and how we can create blank, empty images with it it's time to move on to working with text. Take a look at the following PHP code snippet.

// Some basic setup
$imageWidth = 300;
$imageHeight = 200;
$textFont = "Cyclo.ttf"; $textSize = 15; $textString = "CodingTuts.com"; $positionLeft = 10; $positionTop = 60;
// Set the headers content type
header("Content-type: image/png");

// Create the image
$image = imagecreatetruecolor($imageWidth, $imageHeight);

// Create some colors
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// Fill the background of our image
imagefilledrectangle($image, 0, 0, $imageWidth, $imageHeight, $black);

// Add some text imagettftext($image, $textSize, 0, $positionLeft, $positionTop, $white, $textFont, $textString);

// Output the image to the browser
imagepng($image);

// Destroy the image
imagedestroy($image);

The above piece of code is very similar to the first although we have added in a few things. At the top we now have five new variables defined. These are used throughout the script for various things.We have also added the colour white using the RGB 000 into the $white variable.

Further down the script we have also made use of one extra function -
imagettftext(). This is the function used to add text to an image based on a TrueType font. The font I am using in this example is called Cyclo and is available at FontRack. Simply download it (or a font of your choice) and place it in the same directory as your script.

The imagettftext() function which we have used takes eight parameters which are our image ($image), the text size ($textSize), the text angle (set to 0 in this example), the x and y co-ordinate where the text should be added to the image (bottom-left corner, $positionLeft and $positionTop), the text colour ($white), the font file ($textFont) and then the text string ($textString). By changing the $positionLeft and $positionTop variables you should notice that the text will move position around your image.

By running the above script it produces the following.

4. Making it align center

By now you should have a decent understanding of how to create a blank image in GD and then add some basic text to it. This means we can now move on to the main step of this tutorial which is to align the text center in the image.

Now it would be possible to simply try a load of values for the $positionLeft and $positionTop until your text looked like it was in the center and this technique actually works pretty well. But what if you then decided to resize your image or perhaps use a different font? That would mean spending even more time playing with the number until you got it back in the center.

All of this work can be skipped with just a few extra lines of code which will calculate the exact co-ordinates where our text needs to go. Take a look at the following code.

// Some basic setup
$imageWidth = 300;
$imageHeight = 200;
$textFont = "Cyclo.ttf";
$textSize = 15;
$textString = "CodingTuts.com";

// Set the headers content type
header("Content-type: image/png");

// Create the image
$image = imagecreatetruecolor($imageWidth, $imageHeight);

// Create some colors
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// Fill the background of our image
imagefilledrectangle($image, 0, 0, $imageWidth, $imageHeight, $black);

// Get box info
$box = imagettfbbox($textSize, 0, $textFont, $textString);

//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH = $box[5] - $box[3];

// Calculate the positions
$positionLeft = ($imageWidth - $textW)/2;
$positionTop = (($imageHeight - $textH)/2);

// Add some text
imagettftext($image, $textSize, 0, $positionLeft, $positionTop, $white, $textFont, $textString);

// Output the image to the browser
imagepng($image);

// Destroy the image
imagedestroy($image);

To begin with we have taken away the two variables $positionLeft and $positionTop from the start of our code. We no longer need these because they will be calculated further down.

The first difference here is the use of the
imagettfbbox() function. Basically what this function does is take the selected font, font size and text string and returns an array containing various sizes and measurements. The array contains 8 elements which are:

0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position

Just after that we use two new variables, $textW and $textH which of course represent the width and height of the text. The text width is calculated by subtracting the the lower left corner X position from the lower right corner X position. The text height is calculated by subtracting the lower right corner Y position from the upper right corner Y position.

Now that we have the text width and height we are able to work out the position which our text should go. To find the left position of our text we take the text width from the image width and then divide by 2. To find out the top position of the text we take the text height from the image height and then divide by 2. These calculation results are put into the variables $positionLeft and $positionTop which just like before are used within the imagettftext() function to add the text to our image.

The result of the above script is the following.

As you can see it is now aligned into the center of the image vertically and horizontally. By altering our image size ($imageWidth and $imageHeight) we can see that our script works as it should. Here is the same script using the width 500 and height 100.

Perfect - it is still in the center of our image.

So there you have it - after following this tutorial you should be able to create blank images using GD, add text to them and then align that text to the center of your image.

You can download the source code to this script here.

User comments

Got something you want to say?
  • Marxer
    14-5-2008
    I've been trying to figure out how to align text in the center with images and PHP for a couple of weeks - I finally got it.

    Thanks!
Coding tutorials