我正在尝试制作验证码。要做到这一点,我需要创建一个图像。我正在遵循Nettuts的本教程。要创建它,我需要使用函数imagettftext()。但是每当我尝试运行它时,它都会给我一个错误说
imagettftext():无效的字体文件名
我的代码如下。
<?php
session_start();
$string = '';
for ($i = 0; $i < 5; $i++) {
$string .= chr(rand(97, 122));
}
$_SESSION['random_code'] = $string;
$dir = base_url('assets/fonts/asman.ttf');
$image = imagecreatetruecolor(170, 60);
$color = imagecolorallocate($image, 200, 100, 90);
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, 200, 100, $white);
imagettftext($image, 30, 0, 10, 40, $color, $dir, $_SESSION['random_code']);
?>
以防万一,我正在使用CodeIgniter框架,但我不想使用CI验证码库。
来自 php 手册:
根据 PHP 使用的 GD 库版本,当 fontfile 不以前导/开头时,.ttf 将被附加到文件名中,库将尝试沿库定义的字体路径搜索该文件名。
您不应该为此使用 URL 路径(另请注意,您的 URL 不以 /
开头)
我建议在指定字体文件时使用绝对文件系统路径:
$dir = '/full/path/to/assets/fonts/asman.ttf';
imagettftext($image, 30, 0, 10, 40, $color, $dir, $_SESSION['random_code']);
我确定 CI 有一些功能可以返回应用程序路径,您可以从中引用正确的文件。
你可以试试这个代码 这对我有用
$dir = realpath('assets/fonts/asman.ttf');
我也有类似的问题 - 使用 realpath() PHP 函数解决了它。
以前:
imagettftext($img,$font_size,0,5,5,$color_text,'../fonts/courgetteregular.ttf',$captcha_string);
后:
$font = realpath("../fonts/courgetteregular.ttf");
imagettftext($img,$font_size,0,5,CAPTCHA_HEIGHT - 10,$color_text,$font,$captcha_string);
此外,在标题("图像/png")上注释将有助于故障排除。