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.


  1. $width = 400;  
  2. $height = 100;  
  3.   
  4. $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().


  1. // white background and blue text  
  2. $bg = ImageColorAllocate($im, 255, 255, 255);  
  3.   
  4. // grey border  
  5. $border = ImageColorAllocate($im, 207, 199, 199);  
  6. ImageRectangle($im, 0, 0, $width - 1, $height - 1, $border);  

Set the text and its color:


  1. $text = 'This is my photo description text.';  
  2.   
  3. $textcolor = ImageColorAllocate($im, 0, 0, 255);  

Now we need to setup the font size and determine the font height and width.


  1. // Font Size  
  2. $font = 3;  
  3.   
  4. $font_width = ImageFontWidth($font);  
  5. $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.

Continue with this tutorial


views 10506
  1. Add New Comment