You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP给图片添加文字失败,请求排查代码问题

问题排查与修复建议

我帮你梳理下这段PHP代码里导致无法添加文字的几个核心问题,以及对应的修复方案:


1. 错误使用imageloadfont函数

你写了$font = @imageloadfont($jpg_image);,但imageloadfont的参数应该是字体文件路径(比如.gdf格式的系统字体),而不是你传入的图像资源$jpg_image。更关键的是,你后面实际用的是imagettftext(加载TrueType字体的函数),这两行代码完全多余,还因为参数错误产生了警告(你加了@屏蔽了错误提示,导致你看不到问题)。

直接删掉这两行无用代码:

$font = @imageloadfont($jpg_image);
$fontSize = imagefontwidth($font);

2. 字体路径与权限问题

你指定的字体路径$font_path = 'font/arial.ttf';需要满足两个条件:

  • 服务器上确实存在这个路径和字体文件
  • PHP进程有读取该文件的权限

如果找不到字体文件,imagettftext会直接执行失败。建议换成服务器上肯定存在的字体路径,比如:

  • Linux系统:/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
  • Windows系统:C:\Windows\Fonts\arial.ttf

3. PNG透明通道处理问题

你的原图是PNG格式,可能带有透明通道,但你创建的画布用了白色背景填充,直接复制图像会丢失透明效果,甚至可能导致文字显示异常。可以修改为支持透明的画布:

// 创建画布后添加这两行,启用透明支持
imagesavealpha($canvas, true);
$trans_color = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
imagefill($canvas, 0, 0, $trans_color);

同时删掉原来的白色背景填充代码:

// 删掉这两行
$bcolor = imagecolorallocate( $canvas, 255, 255, 255 );
imagefilledrectangle( $canvas, 0, 0, $orig_width, ($orig_height + 40), $bcolor );

4. 保存目录的存在性与权限

你把图片保存到upload目录,需要确保这个目录存在,并且PHP有写入权限。可以添加目录检查与创建逻辑:

$path = 'upload';
if (!is_dir($path)) {
    mkdir($path, 0755, true); // 递归创建目录
}

5. 文字坐标的合理性

imagettftext的x坐标设为0,可能导致文字紧贴左边缘,部分字体可能显示不全,建议调整为带偏移的数值,比如:

imagettftext( $canvas, 13, 0, 10, $orig_height + 25, $color, $font_path, $text) ;

修复后的完整代码示例

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); // 开启错误显示,方便调试

$thumb_src = 'copyright-symbol.png'; 
$explode = explode('.', $thumb_src); 
$extension = strtolower(end($explode)); 
$file_name = basename($thumb_src); 

$jpg_image = imagecreatefrompng($thumb_src); 
$orig_width = imagesx($jpg_image); 
$orig_height = imagesy($jpg_image); 

// 创建支持透明的画布
$canvas = imagecreatetruecolor($orig_width, $orig_height + 40); 
imagesavealpha($canvas, true);
$trans_color = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
imagefill($canvas, 0, 0, $trans_color);

// 复制原图到画布
imagecopyresampled($canvas, $jpg_image, 0, 0, 0, 0, $orig_width, $orig_height, $orig_width, $orig_height); 

// 替换为你服务器上存在的字体路径
$font_path = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; 
$path = 'upload'; 

// 确保上传目录存在
if (!is_dir($path)) {
    mkdir($path, 0755, true);
}

$text = 'cc-by-nd-'; 
$color = imagecolorallocate($canvas, 0, 0, 0); 

// 添加文字,调整x坐标避免贴边
imagettftext($canvas, 13, 0, 10, $orig_height + 25, $color, $font_path, $text); 

// 保存图片
imagepng($canvas, $path . '/' . $file_name); 

// 释放内存
imagedestroy($canvas);
imagedestroy($jpg_image);
?>

内容的提问来源于stack exchange,提问作者Shibbir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:00:49