php 8.6用gd绘制中文时,需要安装支持freetype的gd并提供实际存在、包含所需字形的字体文件。居中位置应根据imagettfbbox返回的全部角点计算,而不是按字符数估算;imagettftext的y坐标表示基线,不是文字顶边。

PHP手册中的PHP: imagettfbbox - Manual
准备字体与画布
下面使用站点自行部署的字体文件fonts/NotoSansSC-Regular.ttf。字体名称只是示例,应确认真实文件、授权和中文覆盖范围;缺字时更换合适字体,不把空白方框当成编码错误。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

PHP手册中的PHP: imagettftext - Manual
按四个角点计算位置
<?php
if (!extension_loaded('gd') || !function_exists('imagettfbbox')) {
throw new RuntimeException('需要GD和FreeType');
}
$font = __DIR__ . '/fonts/NotoSansSC-Regular.ttf';
if (!is_readable($font)) throw new RuntimeException('字体不可读');
$text = 'PHP中文教程'; $size = 30; $width = 700; $height = 240;
$box = imagettfbbox($size, 0, $font, $text);
if ($box === false) throw new RuntimeException('测量失败');
$xs = [$box[0], $box[2], $box[4], $box[6]];
$ys = [$box[1], $box[3], $box[5], $box[7]];
$left = min($xs); $right = max($xs);
$top = min($ys); $bottom = max($ys);
if ($right-$left > $width-40 || $bottom-$top > $height-40) {
throw new RuntimeException('文字超出留白范围');
}
$im = imagecreatetruecolor($width, $height);
if ($im === false) throw new RuntimeException('创建画布失败');
imagefill($im, 0, 0, imagecolorallocate($im, 248, 250, 252));
$ink = imagecolorallocate($im, 24, 40, 60);
$x = (int) round(($width-($right-$left))/2-$left);
$y = (int) round(($height-($bottom-$top))/2-$top);
if (imagettftext($im,$size,0,$x,$y,$ink,$font,$text) === false) {
throw new RuntimeException('绘制失败');
}
if (!imagepng($im, __DIR__.'/title.png')) {
throw new RuntimeException('输出失败');
}结果检查与长文本
检查文件实际生成、中文是否缺字及四周留白。长标题应先按业务规则分行,再分别测量每行;单次bbox并不负责自动换行。接口签名适用于PHP 8.6,但这些能力并非8.6首次新增。


















