imagettftext说字体文件名无效

时间:2013-09-07 19:56:29

标签: php image image-processing gd imagettftext

我正在尝试制作验证码。要做到这一点,我需要创建一个图像。我正在关注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验证码库。

3 个答案:

答案 0 :(得分:1)

来自php manual

  

根据PHP使用的GD库的版本,当fontfile不以前导/然后.ttf将附加到文件名时,库将尝试沿库搜索该文件名 - 已定义的字体路径

你不应该使用url路径(还要注意你的网址不是以/开头)

我建议在指定字体文件时使用绝对文件系统路径:

$dir = '/full/path/to/assets/fonts/asman.ttf';
imagettftext($image, 30, 0, 10, 40, $color, $dir, $_SESSION['random_code']);

我确信CI有一些函数可以返回您可以引用正确文件的应用程序路径。

答案 1 :(得分:0)

您可以尝试使用此代码对我来说有用

   $dir = realpath('assets/fonts/asman.ttf');

答案 2 :(得分:0)

我遇到了类似的问题-使用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);

此外,对标头('image / png')进行注释将有助于进行故障排除。

相关问题