Page 1 of 1

PHP - Center text on image

Posted: 31 Mar 2015, 16:30
by PloMar
Hello,
I have the following code that saves on the server a png image generated with php.
In that image I add a text (using imagettftext()), but would like it to be horizontally and vertically centered.
How to center the text on image using PHP GD, knowing that the text and the image sizes are variable?
This is the code:

Code: Select all

<?php
$text = 'CoursesWeb.net';
$font_size = 20;  // Font size is in pixels.
$font_file = 'verdana.ttf';  // path to your font file
$img = 'image_1.jpg';  // path to image
$img2 = 'imgs/image.png';  // path & name of the image to save on server

// get the image in php
$im = imagecreatefromjpeg($img);

// text color
$clr = imagecolorallocate($im, 255, 222, 2);

// starting x and y coordinates for the text
$x = 35;
$y = 80;

// Add text to image:
imagettftext($im, $font_size, 0, $x, $y, $clr, $font_file, $text);

// save the image on server
imagepng($im, $img2, 9);

// Destroy image in memory to free-up resources:
imagedestroy($im); 

PHP - Center text on image

Posted: 31 Mar 2015, 16:39
by MarPlo
Hi,
You can use the imagettfbbox() function, it returns an array with 8 elements representing four points making the bounding box of the text.
Using those coords, you can calculate the width and height of the text, then it's simple arithmetic to center that on your image.
Example:

Code: Select all

<?php
$text = 'CoursesWeb.net';
$font_size = 20;  // Font size is in pixels.
$font_file = 'verdana.ttf';  // path to your font file
$img = 'image_1.jpg';  // path to image
$img2 = 'imgs/image.png';  // path & name of the image to save on server

// Retrieve bounding text-box:
$txt_space = imagettfbbox($font_size, 0, $font_file, $text);

// Determine text width and height
$txt_width = abs($txt_space[4] - $txt_space[0]);
$txt_height = abs($txt_space[3] - $txt_space[1]);

// get the image in php
$im = imagecreatefromjpeg($img);

// text color
$clr = imagecolorallocate($im, 255, 222, 2);

// Get image Width and Height
$image_width = imagesx($im);  
$image_height = imagesy($im);

// set starting x and y coordinates for the text, so that it is horizontally and vertically centered
$x = abs($image_width - $txt_width) /2;
$y = abs($image_height - $txt_height) /2;

// Add text to image:
imagettftext($im, $font_size, 0, $x, $y, $clr, $font_file, $text);

// save the image on server
imagepng($im, $img2, 9);

// Destroy image in memory to free-up resources:
imagedestroy($im);