imagettftext(): Could not find/open font error mes

2019-07-10 03:18发布

问题:

I'm trying to read a captcha image in a form.

Here is the form code:

<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>

And this is the generate.php file:

<?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);
?>

As you can see I have commented out the header() to see what error this page returns. And the error is this:

Warning: imagettftext(): Could not find/open font on line 25

Line 25:

imagettftext($image, $font_size, 0, 15, 30, $text_color, 'font.ttf', $text);

I don't know why this error happens because the font.ttf file is placed correctly in the same directory.

So what is going on here guys ?!

回答1:

You need to provide the real path to the font file. Try this:

realpath('path/to/you/font.ttf');

This approach is working for me.



回答2:

Based on Maicon Perin answer.

    $image = Image::canvas(750, 300, '#f3f3f3');
    $image->text($title, 375, 150, function($font) {
        $font->file(realpath('fonts/font-file.ttf'));
        $font->size(44);
        $font->color('#ffffff');
        $font->align('center');
        $font->valign('center');
    });

You just need to add font file to | public/fonts/font-file.ttf