phplaravellaravel-9laravel-controller

Laravel 9: imagettftext(): Invalid font filename


I have a Controller method like this:

public function singleChar($text)
{
   $font = 'SansBold.ttf';

   ...

   imagettftext($img, $size, $angle + 5, $textX + 5, $textY + 10, $shadowgbColor, $font, $text);

   ... 
 }

But I'm afraid that's not right because I get this error:

imagettftext(): Invalid font filename

And I think this error occurs because I have wrongly called the font SansBold.ttf. So I wonder what the correct way of calling this font inside this Controller Method is? And also, where should I place the font?

Note that I'm using PHP v8 and also enabled GD Library by uncommenting ;extension=gd inside php.ini. I'm stuck with this and would appreciate any idea or suggestion.


Solution

  • you need to specify the full path to the font file.

    it is better to use the public folder to store the font (if you need to have public access to it) or the storage/app folder (if you only use it inside your laravel application)

    In the first case, getting the path will look like this:

    $font = public_path('fonts/SansBold.ttf'); // your file here: public/fonts/SansBold.ttf
    

    In the second case:

    $font = storage_path('app/fonts/SansBold.ttf'); // your file here: storage/app/fonts/SansBold.ttf