Question

Using the imagettftext function from the PHP GD library, one can only draw text that is left-aligned onto an image. At least so it would seem, perhaps I'm missing something.

How can I control the alignment of the text drawn onto an image? i.e. left / center / right (/ justified - not necessary, but useful)

I should mention that the alignment is visible when the drawn text contains multiple lines (e.g. "bla bla bla/nAnd another line of bla.").

Was it helpful?

Solution

with imagettftext() you're not writing into some kind of "box" but just at the given coordnates. to alingn the text properly, you'll have to calculate the correct coordinates to make it "look like" it's right-aligned or centered.

to do so, you can use imagettfbox() to get the size of your text - the rest is simple math:

  • to right-align add [textarea-width]-[textwidth] to your X-coordinate
  • to center add ([textarea-width]-[textwidth]) / 2 to your X-coordinate

(*textarea = the area you want to write the text at in your image - it's size should be known to you)

OTHER TIPS

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(255, 255, 255));
$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('left', 'top');
// or like this:
// $textbox->setTextAlign('right', 'top');
// $textbox->setTextAlign('center', 'top');
// $textbox->setTextAlign('center', 'bottom');
// $textbox->setTextAlign('right', 'center');

// it accepts multiline text
$textbox->draw("text to write on picture\nanother line below");

Demonstration:

demo

The function accepts x and y positional coordinates.

    array imagettftext ( resource $image, 
                         float $size, 
                         float $angle, 
                         int $x, 
                         int $y, 
                         int $color, 
                         string $fontfile, 
                         string $text )

Take a look at http://php.net/manual/en/function.imagettftext.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top