Search code examples
phpimagegdimagettftext

Right align text in an image with imagettftext(), PHP


I am setting up dynamic forum signature images for my users and I want to be able to put their username on the image. I am able to do this just fine, but since usernames are different lengths and I want to right align the username, how can I go about doing this when I have to set x & y coordinates.

$im = imagecreatefromjpeg("/path/to/base/image.jpg");
$text = "Username";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);

imagettftext($im, 10, 0, 217, 15, $black, $font, $text);
imagejpeg($im, null, 90);

Solution

  • Use the imagettfbbox function to get the width of the string and then subtract that from the width of the image to get the starting x-coordinate.

    $dimensions = imagettfbbox($fontSize, $angle, $font, $text);
    $textWidth = abs($dimensions[4] - $dimensions[0]);
    $x = imagesx($im) - $textWidth;