PHP - Center text on image
Posted: 31 Mar 2015, 16:30
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:
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);