linux提示Warning: imagettftext(): Could not find/open font錯誤

來源:互聯網
上載者:User

(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';    //絕對路徑

這樣驗證碼就可以正常顯示了

從上面的函數用法來看就是打不開字型了,也就是一個非常簡單路徑問題了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.