Jaquarh
Jaquarh

Reputation: 6693

How to centre text in the middle of a created PNG image

I have created the image like so:

$altoRouter->map('GET|POST', '/public/images/generate/[*:name]', function($string) {
    $font = 100;
    $im = imagecreatetruecolor($font * strlen($string['name']) + 50, 300);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $white);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagettftext($im, $font, 0, 0, $font - 3, $black, IEZON_ROOT . "/public/uploads/NovaSquare.ttf", strtoupper($string['name']));
    header("Content-type: image/png");
    imagepng($im);
    imagedestroy($im);
});

Which gives me this output if I do /public/images/generate/example:



However, as you can see, the text is left aligned and not in the centre of the image. Is there any way I can achieve this?

Upvotes: 1

Views: 48

Answers (1)

Jaquarh
Jaquarh

Reputation: 6693

Thanks to @ceejayoz I used this:

$altoRouter->map('GET|POST', '/public/images/generate/[*:name]', function($string) {
    $font = 100;
    $im = imagecreatetruecolor($font * strlen($string['name']) + 200, 300);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $white);
    $black = imagecolorallocate($im, 0, 0, 0);

    $width = $font * strlen($string['name']) + 200;
    $centerX = $width / 2;
    list(,,$right,,,,) = imageftbbox($font, 0, IEZON_ROOT . "/public/uploads/NovaSquare.ttf", strtoupper($string['name']));
    $left_offset = $right / 2;
    $x = $centerX - $left_offset;
    imagettftext($im, $font, 0, $x, 200, $black, IEZON_ROOT . "/public/uploads/NovaSquare.ttf", strtoupper($string['name']));
    header("Content-type: image/png");
    imagepng($im);
    imagedestroy($im);
});

Which now centres perfectly.

Upvotes: 3

Related Questions