-1

I'm trying to add text to an image in PHP with imagettftext. However, it doesn't seem to accept any .ttf file and keeps giving the errors: 'Could not find/open font' and 'Invalid font filename'. The file path is localhost/fonts/arial.ttf

I've tried relative paths, absolute paths, changing / to \ , tried putting ../ before the path but nothing seems to work. I've checked the GD version and its the 2.1.0 and the FreeType Linkage is 'with freetype' whatever that means.

<?php

    $output = "pics/email.png";

    $x = 720;
    $y = 480;
    $image = imagecreate($x, $y);

    //colors to use (rgb)

    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 0, 0, 0);

    $font = 'fonts/arial.ttf';

    $text1 = imagettftext($image, 40, 0, 20, 40, $black, $font, "Text Sample");


    imagejpeg($image, $output);

    var_dump(gd_info());



    ?>

I'd be thankful if anyone could give a working answer.

edluis97
  • 62
  • 10
  • 3
    Try using the full file path for the font instead of a relative file path. – aynber Apr 04 '19 at 12:25
  • 1
    localhost is not a path, it's a URL. So yeah, do as @anynber says – Unamata Sanatarai Apr 04 '19 at 12:26
  • From the documentation: "Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path." So yeah, always use an absolute path there, or you could run into trouble when porting, even if it does work locally. – Amunium Apr 04 '19 at 12:28
  • Sorry for asking but by full path do you mean C://.../fonts/arial.ttf? – edluis97 Apr 04 '19 at 12:29
  • 1
    See also https://stackoverflow.com/questions/10366679/warning-imagettftext-function-imagettftext-could-not-find-open-font-in-ho/10366726#10366726 -- yes use the full `C:/path/to/fonts/arial.ttf` – Michael Berkowski Apr 04 '19 at 12:32
  • So yours might work if you just used `fonts/Arial` without .ttf, or it might work if you used `putenv('GDFONTPATH=' . realpath('./fonts'));` and specify the font as just `Arial` – Michael Berkowski Apr 04 '19 at 12:33
  • Thank you very much. It works like a charm. – edluis97 Apr 04 '19 at 12:35
  • @mario: The intermediate duplicate has been deleted, breaking the chain. Could you please edit the dupe list for this question to point directly to e.g. https://stackoverflow.com/questions/10366679/warning-imagettftext-function-imagettftext-could-not-find-open-font-in-ho? Thanks. – Ilmari Karonen May 14 '19 at 11:15

1 Answers1

0

Already solved it, thanks to the people in the comment section.

I just had to use the full file path (C://.../fonts/arial.ttf)

edluis97
  • 62
  • 10