DEV Community

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

Posted on

4 1

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.

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video β†’

Top comments (0)

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay