如何在创建的PNG图像中间居中放置文本

时间:2018-11-08 19:51:18

标签: php image png

我已经这样创建了图像:

$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);
});

如果我执行/public/images/generate/example,哪个会给我此输出:



但是,如您所见,文本保持左对齐,而不是在图像的中心。我有什么办法可以做到这一点?

1 个答案:

答案 0 :(得分:3)

感谢@ceejayoz,我使用了这个

$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);
});

现在可以完美地居中了。