PHP GD How to center a text on an image using GD
Dec 10, 2008
Author: christina
This is a snippet which centers a text on an image using the GD Library.
First, we create the image using the ImageCreate() function. Here we set the width & height.
- $width = 400;
- $height = 100;
- $im = ImageCreate($width, $height);
The we use ImageColorAllocate() to fill the image with white background and set the border’s color, which is eventually created with ImageRectangle().
- // white background and blue text
- $bg = ImageColorAllocate($im, 255, 255, 255);
- // grey border
- $border = ImageColorAllocate($im, 207, 199, 199);
- ImageRectangle($im, 0, 0, $width - 1, $height - 1, $border);
Set the text and its color:
- $text = 'This is my photo description text.';
- $textcolor = ImageColorAllocate($im, 0, 0, 255);
Now we need to setup the font size and determine the font height and width.
- // Font Size
- $font = 3;
- $font_width = ImageFontWidth($font);
- $font_height = ImageFontHeight($font);
In the next lines we determine the text’s width and height. Then, based on the information we have, the X, Y coordonates of the upper left corner can be calculated.
views 4116



