Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center aligning multiple lines of text with GD and PHP

Tags:

php

gd

I'm trying to print multiple lines of text on an image and center align them.

i.e.

    This is
A string of text

Right now, I only have the left position for the whole string. Any shortcuts on getting that to work? I think it might have to be a getttfbox on the whole string, then an explode on the line breaks, then center the new text inside that larger ttfbox. That's a pain in the ass...

EDIT: Came up with a solution:

    foreach ( $strings as $index => $string ) {
        $parts = explode ( "\n", $string['string'] );
        if ( count ( $parts ) > 1 ) {
            $bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $string['string'] );
            $width = $bounds[2] - $bounds[0];
            $height = $bounds[3] - $bounds[5];
            $line_height = $height / count ( $parts );

            foreach ( $parts as $index => $part ) {
                $bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $part );
                $new_width = $bounds[2] - $bounds[0];
                $diff = ( $width - $new_width ) / 2;
                $new_left = $string['left'] + $diff;

                $new_string = $string;
                $new_string['left'] = $new_left;
                $new_string['top'] = $string['top'] + ($index * $line_height);
                $new_string['string'] = $part;
                $new_strings[] = $new_string;
            }
        }
    }

    if ( $new_strings )
        $strings = $new_strings;

In this case, each $string is an array with some information about how and what to print. Hope that helps someone.

like image 722
Seamus James Avatar asked Mar 15 '12 21:03

Seamus James


1 Answers

You can use stil/gd-text class. Disclaimer: I am the author.

<?php
use GDText\Box;
use GDText\Color;

$img = imagecreatefromjpeg('image.jpg');

$textbox = new Box($img);
$textbox->setFontSize(12);
$textbox->setFontFace('arial.ttf');
$textbox->setFontColor(new Color(0, 0, 0));
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);

// now we have to align the text horizontally and vertically inside the textbox
$textbox->setTextAlign('center', 'top');
// it accepts multiline text
$textbox->draw("This is\na string of text");

Demonstration:

demo

like image 177
stil Avatar answered Oct 13 '22 22:10

stil