PHP imagettftext() - nothing is displaying

北战南征 提交于 2019-12-11 20:14:29

问题


Trying to display a font using the GD library. There is indeed an image there, it's just that theres nothing displaying.

PHP:

header('Content-Type: image/png');

$font = $_GET['font'];

// Create the image
$image = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($image, 255, 255, 255);
$grey = imagecolorallocate($image, 128, 128, 128);
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 399, 29, $white);

// The text to draw
$text = 'The Quick Brown Fox Jumps over the Lazy Dog';
$font = '/Aller/' . $font;


// Add the text
imagettftext($image, 20, 0, 10, 20, $black, $font, $text);

imagepng($image);

HTML:

<img src="fontgen.php?font=Aller_Rg.ttf" alt="" />

The font resides in fonts/Aller/Aller_Rg.tff

What am I doing wrong?


回答1:


The problem seems to be the $font variable. 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.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

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

You also said that the font resides in fonts/Aller/ directory. Whereas, in your script, there is no reference to the fonts directory.




回答2:


The code is all correct except this part

$font = '/Aller/' . $font;

It tries the absolute path '/Aller/Aller_Rg.tff' not 'Aller/Aller_Rg.tff'

Changing it to $font = 'Aller/' . $font; should work.

Also you should check the error log, it should mention Invalid font filename

When in doubt remove header('Content-Type: image/png'); for debugging.



来源:https://stackoverflow.com/questions/16995583/php-imagettftext-nothing-is-displaying

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!