【发布时间】:2021-07-03 17:11:38
【问题描述】:
我正在尝试仅水平对齐 php gd 库中图像上的文本,就像您使用 "text-align: center" 所做的那样,因此如果文本太大,则文本不会超出图像。
<?php
// (A) OPEN IMAGE
$img = imagecreatefrompng('LOGO.PNG');
// (B) WRITE TEXT
$txt = "Divine Magnificent Endurance";
$font = "C:/xampp/htdocs/testImages/ArialCE.ttf";
$white = imagecolorallocate($img, 0, 0, 0);
$width = imagesx($img);
$height = imagesy($img);
$text_size = imagettfbbox(24, 0, $font, $txt);
$text_width = max([$text_size[2], $text_size[4]]) - min([$text_size[0], $text_size[6]]);
$text_height = max([$text_size[5], $text_size[7]]) - min([$text_size[1], $text_size[3]]);
$centerX = CEIL(($width - $text_width) / 2);
$centerX = $centerX<0 ? 0 : $centerX;
$centerY = CEIL(($height - $text_height) / 1.3);
$centerY = $centerY<0 ? 0 : $centerY;
imagettftext($img, 18, 0, $centerX, $centerY, $white, $font, $txt);
imagesavealpha($img, true);
// (C) OUTPUT IMAGE
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
【问题讨论】: