Question

I'm using the following code in the test.php file to generate an image from a text.

<?php
error_reporting(E_ALL);

// Set the content-type
header('Content-Type: image/png');

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

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

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = '/home/axxxxxxx/public_html/font.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

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

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);

?>

Then I'm trying to display the image in the test2.php as follows

<?php
echo "<img src=\"/test.php\" />";
?>

All I get is the default broken image icon. The path to the font file and image url is correct. All file permission are at 777. The servers do have the GD library.

What might I be doing wrong?

Was it helpful?

Solution 3

Found the answer. As Danak suggested, I saved the file as UTF-8 Without BOM using the notepad++. Then Is simply started displaying the image correctly.

OTHER TIPS

This is caused by the missing font. Please copy the font file in the test.php directory and change code:

$font = '/home/axxxxxxx/public_html/font.ttf';

to

$font = 'font.ttf';

Hope it helps.

My issue was a wrong offset. The image was showing nothing, no text, no errors in the source code, just a blank file. The paths were correct. I thought there was an error in the ttf font but turns out it was just wrong positioning.

Here's what helped me to see a bit of the text:

imagettftext($im, 20, 0, 20, 20, $fg, $font, $text);

This shows a bit of text on the top right.

Full working code:

    putenv('GDFONTPATH=' . dirname(__FILE__));
    $font = 'arial'; // located next to the script
    imagettftext($im, 20, 0, 20, 20, $fg, $font, $text);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top