imagestring - 获取字符串长度的大小(以像素为单位)

imagestring - Get the size of the string lengh in pixels

您好, 只是想提前提到这不是重复的。 我已经看过类似的帖子,但所有这些都使用特定的字体,但情况并非如此。 我正在使用默认字体编号 3(对于此示例),我希望能够计算输出大小并将其放在 $canvas

的正中心
imagestring($canvas,3,imagesx($canvas),imagesy($canvas),$myString,imagecolorallocate($canvas,239,13,177));

我知道如何进行计算以将其置于中心位置这很容易,唯一遗漏的参数是考虑到字体编号 3 的字符串的确切像素大小 (x/y)。 考虑到字体编号 3.

我的字符串的像素 (x/y)

imagettfbbox and imagettftext 将完成工作:

//setup
$font     = '<path to font>';
$string   = 'My String';
$fontSize = 12;

//getting width and height
$bBox   = imagettfbbox($fontSize, 0, $font, $string);
$width  = $bBox[2] - $bBox[0];
$height = $bBox[1] - $bBox[7];

//drawing in the center
imagettftext($canvas, $fontSize, 0, (imagesx($canvas) - $width)/2, (imagesy($canvas) - $height)/2, $color, $font, $string);

经过一番研究,我发现imagestring中使用的字体没有标准的宽度或间距。在我的 PHP 实现中,字体 3 似乎有 6 x 9 像素字符,1 像素间距,等宽,所以 7 * strlen 应该给出相当准确的宽度,9 应该给出高度(我假设你只是使用居中一行)的字符串图像。但是,这可能是特定于平台或实现的,因此如果它不适合您,您必须自己衡量。

这个解决方案是如果你必须使用 imagestring(),当然——使用 imagettftext() 和 imagettfbbox() 对于精确测量会更好,正如 Waldson 所建议的。

不使用特定字体更新了答案。 PHP 嵌入的字体确实是等宽的(经过测试和工作):

$font           = 3;
$img            = imagecreatetruecolor(500, 500);
$text           = "Waldson Patricio";
$color          = imagecolorallocate($img, 255, 255, 255);
$size           = strlen($text);

$tw             = $size * imagefontwidth($font);
$th             = imagefontheight($font);



imagestring($img, $font, (imagesx($img) - $tw) / 2 , (imagesy($img) - $th) / 2, $text, $color);
header('Content-type:image/jpeg');
imagejpeg($img);