php imagefttext 是 PHP GD 库中用于在图像上绘制 TrueType 字体文本的核心函数,全称为 “FreeType text”。该函数支持任意字体、任意大小、任意角度的文本绘制,是生成验证码、图片水印、图文合成、海报生成等场景不可或缺的工具函数。
相较于早期的 imagestring()、imagestringup() 等基于内置字体的函数,php imagefttext 具有显著优势:
其函数原型如下:
array|false imagefttext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text , array $extrainfo = ? )
返回值为一个包含 8 个元素的数组,依次表示文本边界框的四个角坐标(左上、右上、右下、左下):[x1,y1,x2,y2,x3,y3,x4,y4]。若失败则返回 false。
⚠️ 注意:php imagefttext 依赖系统安装的 FreeType 库。若 GD 扩展未启用 FreeType 支持,调用将直接报错。可通过 phpinfo() 或 gd_info() 函数检查是否包含 “FreeType Support” 项。
| 参数名 | 类型 | 说明 | 注意事项 |
|---|---|---|---|
| image | resource | 由 imagecreatefrom* 系列函数创建的图像资源(如 imagecreatefrompng()) | 必须为有效 GD 图像资源;否则报警告 |
| size | float | 字体大小(单位:像素) | 非整数(如 12.5)可实现微调;建议 8~72 范围内使用 |
| angle | float | 文本旋转角度(0°=水平,90°=顺时针90度) | 角度以逆时针方向为正;0~360 范围内自动归一化 |
| x, y | int | 起始绘制点坐标(文本基线左端点) | 坐标系原点在图像左上角;y 值指文本基线位置 |
| color | int | 颜色索引(由 imagecolorallocate() 创建) | 真彩色图像(true color)中建议使用 imagecolorallocatealpha() 支持透明度 |
| fontfile | string | 字体文件绝对路径或相对路径 | 路径错误将导致函数失败;建议使用 realpath() 验证 |
| text | string | 待绘制的文本内容 | 支持 UTF-8 编码;需确保 GD 库开启 UTF-8 支持 |
| extrainfo | array | 额外配置数组(可选) | 支持 'linespacing'(行间距)、'flags'(渲染标志)等 |
从 PHP 7.3.0 起,php imagefttext 支持通过 extrainfo 数组传递高级渲染参数:
php imagefttext 对中文的支持高度依赖字体文件本身是否包含中文字形。常见问题包括:
msyh.ttc(微软雅黑)、SimSun.ttc(宋体)、NotoSansCJK(思源黑体)等,并确保路径正确mb_internal_encoding('UTF-8');确保字体文件为 UTF-8 编码(部分 TTF 字体为 GBK,需转换)Source Han Sans SC(仅约 15MB)<?php
header("Content-Type: image/png");
$im = imagecreatetruecolor(600, 200);
$bg = imagecolorallocate($im, 255, 255, 255);
$textColor = imagecolorallocate($im, 0, 0, 0);
// 使用思源黑体
$font = realpath('NotoSansSC-Regular.otf');
$text = "php imagefttext 支持中文绘制";
// 绘制文本(角度0)
imagefttext($im, 24, 0, 20, 50, $textColor, $font, $text);
// 绘制带阴影的文本(角度15)
$shadowColor = imagecolorallocate($im, 200, 200, 200);
imagefttext($im, 24, 15, 23, 53, $shadowColor, $font, $text);
imagefttext($im, 24, 15, 20, 50, $textColor, $font, $text);
imagepng($im);
imagedestroy($im);
原因:字体文件路径错误、权限不足或字体文件损坏
排查步骤:
is_file($fontfile) 验证路径有效性/var/www/fonts/...)extension_loaded('gd') && gd_info()['FreeType Support']原因:字体文件格式不兼容或损坏(常见于从 Windows 复制的 TTF)
解决方案:
原因:字体不支持中文 / 编码不匹配 / 字符集截断
调试技巧:
var_dump(iconv_strlen($text, 'UTF-8')) 检查实际字符长度"中" 确认是否字体缺失字形mb_detect_encoding($text) 确认编码function debug_imagefttext($text, $fontfile, $size, $angle) {
$bbox = imageftbbox($size, $angle, $fontfile, $text);
echo "文本边界框:\n";
print_r($bbox);
echo "宽度 = " . ($bbox[2] - $bbox[0]) . "px\n";
echo "高度 = " . ($bbox[5] - $bbox[1]) . "px\n";
}
该函数可提前计算文本尺寸,避免绘制后才发现溢出问题。
字体文件加载是 I/O 密集型操作。建议将字体路径缓存为常量:
define('FONT_PATH', __DIR__ . '/fonts/NotoSansSC-Regular.otf');
避免每次调用时重复解析路径。
当需绘制多行文本时,避免重复创建图像资源:
$im = imagecreatetruecolor(800, 600);
$color = imagecolorallocate($im, 0, 0, 0);
// 逐行绘制
foreach ($lines as $i => $line) {
imagefttext($im, 16, 0, 50, 30 + $i * 24, $color, FONT_PATH, $line);
}
在绘制前获取文本边界,实现精准排版:
$bbox = imageftbbox(20, 0, FONT_PATH, $text);
$textWidth = $bbox[2] - $bbox[0];
$textHeight = $bbox[5] - $bbox[1];
// 居中绘制
$x = ($imageWidth - $textWidth) / 2;
$y = ($imageHeight + $textHeight) / 2;
imagefttext($im, 20, 0, $x, $y, $color, FONT_PATH, $text);
将 TTF 字体转换为 GD 的 CDB 格式(需编译时启用 CDB 支持)可加速加载,但现代 PHP 版本已不推荐使用。
如需生成 1000 个带文字的图片,应批量处理后合并,而非单张绘制:
// 错误做法
for ($i=0; $i<1000; $i++) {
$im = imagecreatetruecolor(...);
imagefttext($im, ...);
imagepng($im);
}
// 优化做法
$baseIm = imagecreatetruecolor(200, 100);
for ($i=0; $i<1000; $i++) {
$text = "ID:$i";
imagefttext($baseIm, 16, 0, 10, 50, $color, FONT_PATH, $text);
imagecopy($finalIm, $baseIm, 0, 0, 0, 0, 200, 100);
imagefill($baseIm, 0, 0, $bg); // 清空画布
}
Imagick 是基于 ImageMagick 的 PHP 扩展,支持更强大的文字渲染能力:
示例代码:
$imagick = new Imagick();
$imagick->newImage(600, 200, new ImagickPixel('white'));
$draw = new ImagickDraw();
$draw->setFontSize(24);
$draw->setFillColor(new ImagickPixel('black'));
$draw->setFont('/fonts/NotoSansSC-Regular.otf');
$imagick->annotateImage($draw, 20, 50, 0, 'php imagefttext 的替代方案');
$imagick->setImageFormat('png');
header('Content-Type: image/png');
echo $imagick;
优势:支持中文排版更精准,抗锯齿效果更好;劣势:需额外安装 ImageMagick 依赖。
在不更换扩展的前提下,可通过以下方式增强 GD 渲染效果:
imagesetstyle($im, [
IMAGICK_PIXEL_TRANSPARENT => true,
IMG_CROP_DEFAULT => 0
]);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);$color = imagecolorallocatealpha($im, 0, 0, 0, 30); // 透明度 30/127imagecopymerge($im, $shadowIm, $x+2, $y+2, 0, 0, $w, $h, 50);对于复杂排版需求,可结合外部工具链:
典型流程:PHP 生成 HTML 模板 → 调用 Node.js Sharp 渲染 → 返回图片路径
A:通过 angle 参数控制旋转角度(单位:度)。例如绘制 45 度倾斜文字:
$angle = 45;
$x = 100; $y = 100;
imagefttext($im, 20, $angle, $x, $y, $color, FONT_PATH, "旋转文字");
注意:旋转后需重新计算坐标以避免文字截断。
A:使用 imageftbbox 获取实际边界框宽度:
$bbox = imageftbbox(20, 0, FONT_PATH, "php imagefttext");
$width = $bbox[2] - $bbox[0]; // 精确像素宽度
避免使用 mb_strwidth(仅估算,不精确)。
A:不直接支持。SVG 字体需先转换为 TTF/OTF,或改用 Imagick 的 SVG 渲染能力。
A:需手动分词处理。推荐方案:
function wrapText($text, $font, $size, $maxWidth) {
$words = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
$lines = [];
$currentLine = '';
foreach ($words as $char) {
$testLine = $currentLine . $char;
$bbox = imageftbbox($size, 0, $font, $testLine);
if ($bbox[2] - $bbox[0] > $maxWidth) {
$lines[] = $currentLine;
$currentLine = $char;
} else {
$currentLine = $testLine;
}
}
$lines[] = $currentLine;
return $lines;
}
A:按设备像素比放大画布尺寸:
$scale = 2; // Retina 屏幕
$im = imagecreatetruecolor(800*$scale, 200*$scale);
// ... 绘制后缩小
$final = imagecreatetruecolor(800, 200);
imagecopyresampled($final, $im, 0, 0, 0, 0, 800, 200, 800*$scale, 200*$scale);
A:先绘制文字,再用 imageline 绘制下划线:
// 绘制文字
imagefttext($im, 20, 0, $x, $y, $color, FONT_PATH, $text);
// 计算下划线位置
$bbox = imageftbbox(20, 0, FONT_PATH, $text);
$underlineY = $y + 3; // 略低于基线
$underlineStart = $x;
$underlineEnd = $x + ($bbox[2] - $bbox[0]);
imageline($im, $underlineStart, $underlineY, $underlineEnd, $underlineY, $color);