DEV Community

Cover image for Aligning text horizontally and vertically with PHP GD
Onelinerhub
Onelinerhub

Posted on

Aligning text horizontally and vertically with PHP GD

Let's draw text on 400x300 image as example.

Horizontal center align

$im = imagecreatetruecolor(400, 300);

$c_black = imageColorAllocate($im, 0,0,0);
$c_green = imageColorAllocate($im, 46,204,64);
$text = 'Hi';

$font = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';
$p = imagettfbbox(40, 0, $font, $text);

imagettftext($im, 40, 0, (400 - $p[2])/2, 100, $c_green, $font, $text);
imagePng($im, '/tmp/image.png');
Enter fullscreen mode Exit fullscreen mode

We use (400 - $p[2])/2 to calculate x coordinate so our text is centered horizontally. Open original or edit on Github.

Vertical and horizontal center align

$im = imagecreatetruecolor(400, 300);

$c_black = imageColorAllocate($im, 0,0,0);
$c_green = imageColorAllocate($im, 46,204,64);
$text = 'Hi';

$font = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';
$p = imagettfbbox(40, 0, $font, $text);

imagettftext($im, 40, 0, (400 - $p[2])/2, (300 - $p[5])/2, $c_green, $font, $text);
imagePng($im, '/tmp/image.png');
Enter fullscreen mode Exit fullscreen mode

We've used (400 - $p[2])/2to center align text horizontally and(300- $p[5])/2 to get y coordinate so our text is also centered vertically.

Open original or edit on Github.

Top comments (0)