在php中imagettftext — 用 TrueType 字体向图像写入文本了,在其它版本中没有问题唯独在linux中使用imagettftext时出现imagettftext(): Could not find/open font错误了,具体我们来看解决办法。

(PHP 4, PHP 5, PHP 7)

imagettftext — 用 TrueType 字体向图像写入文本

说明

array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )

使用 TrueType 字体将 指定的 text 写入图像。

很多情况下字体都放在脚本的同一个目录下。下面的小技巧可以减轻包含的问题。

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>


最近一个项目在Ubuntn的apache服务器中验证码显示不出来,在CentOS的apache服务器中显示是正常的。以为是PHP配置的问题,但是GD库的开启的,相关服务也都正常,把显示验证码的方法单独拿出来测试,发现报错

Warning: imagettftext(): Could not find/open font

截取部分相关代码:

class Checkcode {
    //设置字体的地址
    private $font;
 
    function __construct() {
        $rand = rand(0, 1);
        if ($rand == 0) {
            $this->font = 'elephant.ttf';
        } else {
            $this->font = 'Vineta.ttf';
        }
    }
 
    /**
     * 生成文字
     */
    private function creat_font() {
        $x = $this->width / $this->code_len;
        for ($i = 0; $i < $this->code_len; $i++) {
            imagettftext($this->img, $this->font_size, rand(-30, 30), $x * $i + rand(0, 5), $this->height / 1.4, $this->font_color, $this->font, $this->code[$i]);
            if ($i == 0)
                $this->x_start = $x * $i + 5;
        }
    }
}

是imagettftext()这个函数报错了,找不到/打不开字体。应该是__construct()函数里指定字体文件出错了。

if ($rand == 0) {
            $this->font = 'elephant.ttf';
        } else {
            $this->font = 'Vineta.ttf';
 }

解决方法:

虽然上面代码指明的是字体文件在当前目录下,但是Ubuntn的apache服务器中还是要给字体文件指定明确的路径

$this->font = './elephant.ttf';    //相对路径
//或者
$this->font = '/var/www/html/project/elephant.ttf';    //绝对路径

这样验证码就可以正常显示了

从上面的函数用法来看就是打不开字体了,也就是一个非常简单路径问题了。

GitHub 加速计划 / li / linux-dash
9
1
下载
A beautiful web dashboard for Linux
最近提交(Master分支:7 个月前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐