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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more