imagettftext():无法找到/打开字体错误消息

5 php fonts captcha image

我正在尝试读取表单中的验证码图像。

这是表单代码:

<form class="login" method="POST" action="">
    <p class="title">Are you human?</p>
    <div id="captchaimage">
        <img src="generate.php">
    </div>
    <input type="text" name="scr" size="6" placeholder="Write what you see here" autofocus/>
    <input class="submititon" type="submit" value="Submit" name="submit"></input>
</form>
Run Code Online (Sandbox Code Playgroud)

这是generate.php文件:

<?php 
session_start();
//header('Content-type: image/jpeg');
$text = $_SESSION['scr'];
$font_size = 26;
$image_width = 100;
$image_height = 40;

$image = imagecreate($image_width, $image_height);
imagecolorallocate($image,255,255,255);
$text_color = imagecolorallocate($image,0,0,0);

for($x=1;$x<=30;$x++){
    $x1 = rand(1, 100);
    $y1 = rand(1, 100);
    $x2 = rand(1, 100);
    $y2 = rand(1, 100);

    imageline($image, $x1, $y1 ,$x2 ,$y2, $text_color);
}

imagettftext($image, $font_size, 0, 15, 30, $text_color, 'font.ttf', $text);
imagejpeg($image);
?>
Run Code Online (Sandbox Code Playgroud)

如您所见,我已注释掉header()以查看此页面返回的错误。错误是这样的:

警告:imagettftext():无法在第 25 行找到/打开字体

25号线:

imagettftext($image, $font_size, 0, 15, 30, $text_color, 'font.ttf', $text);
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会发生这个错误,因为该font.ttf文件正确放置在同一目录中。

那么,伙计们,这是怎么回事?

小智 1

您需要提供字体文件的真实路径。尝试这个:

realpath('path/to/you/font.ttf');
Run Code Online (Sandbox Code Playgroud)

这种方法对我来说很有效。