How to control text alignment for text generated using `imagettftext()`?

Andrei Oniga picture Andrei Oniga · Nov 5, 2012 · Viewed 9.8k times · Source

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.").

Answer

oezi picture oezi · Nov 5, 2012

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)