Center a text on an image using imagestring()

May 10, 2014 | Last tested: May 2015 | 995 views | Comments

Calculate the x and y coordinates of the upper left corner of a string to make it vertically and horizontally centered when using imagestring() in creating an image with custom text in PHP. The function imagefontwidth() will help get the font width, and for the font height, imagefontheight() will be useful.

For example.

Get the x and y positions from a given width, height, and fontSize..

The formula below will be applied to the tutorial Create an image with custom text in PHP, the generated file will just be saved to a different filename, this time the filename is center-a-text-on-an-image-using-imagestring.png.

Formula

/*
 * horizontally and vertically center the text
 * calculate the x and y positions
 */
$xPosition = (($width/2)-((imagefontwidth($fontSize)*strlen($text))/2));
$yPosition = (($height/2)-(imagefontheight($fontSize)/2));

Full Script

//set the desired width and height
$width = 500;
$height = 300;

//set the font size | possible values 1,2,3,4, and 5, where 5 is the biggest
$fontSize = 4;

//set the text
$text = "ConsistentCoder.com";

/*
 * horizontally and vertically center the text
 * calculate the x and y positions
 */
$xPosition = (($width/2)-((imagefontwidth($fontSize)*strlen($text))/2));
$yPosition = (($height/2)-(imagefontheight($fontSize)/2));

//create a new palette based image
$newImg = imagecreate($width,$height);

//set the image background color to black
$bgColor = imagecolorallocate($newImg, 0, 0, 0);

//set the font color to red
$fontColor = imagecolorallocate($newImg, 255, 0, 0);

//write the text on the created image
imagestring($newImg, $fontSize, $xPosition, $yPosition, $text, $fontColor);

//output the image to a file
imagepng($newImg,"center-a-text-on-an-image-using-imagestring.png");

//destroy an image
imagedestroy($newImg);

Result.

Please mouse over here to view the image.