Rohitashv Singhal
Rohitashv Singhal

Reputation: 4557

unable to show text on the image

I want to show some text on an image. I am using the following code :

session_start();
$name = $_SESSION['name'];
$nameLength = strlen($name); // gets the length of the name
$randomNumber = rand(0, $nameLength - 1); // generates a random number no longer than the name length
$string = ucfirst(substr($name, $randomNumber, 1)); // gets the substring of one letter based on that random number
$im = imagecreatefromjpeg("love.jpg");
$text = "  First Letter of Your partner's name is";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);
$black1 = imagecolorallocate($im, 255, 0, 0);
imagettftext($im, 32, 0, 380, 430, $black, $font, $text);
imagettftext($im, 52, 0, 630, 530, $black1, $font, $string);
imagejpeg($im, null, 90);

but on localhost this code is showing the text on the image but when I am uploading it to server then it is showing only image, text is not shown on this image ? what may be the problem?

$_SESSION['name'] is value when I login to facebook and save the name of the user into $_SESSION

I have uploaded the above code on the server :

http://rohitashvsinghal.com/fb/login.php

Upvotes: 1

Views: 56

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

The font must exist in the location specified obviously and the fullpath to the font works best in my experience.

<?php

    session_start();
    $name = $_SESSION['name'];
    $nameLength = strlen($name);
    $randomNumber = rand(0, $nameLength - 1);
    $string = ucfirst(substr($name, $randomNumber, 1));
    $im = imagecreatefromjpeg("love.jpg");
    $text = "  First Letter of Your partner's name is";

    /* Either use the fullpath or the method given below from the manual */
    $fontpath=$_SERVER['DOCUMENT_ROOT'].'/path/to/fonts/';
    putenv('GDFONTPATH='.realpath( $fontpath ) );

    $fontname='arial.ttf';
    $font = realpath( $fontpath . DIRECTORY_SEPARATOR . $fontname );


    $black = imagecolorallocate($im, 0, 0, 0);
    $black1 = imagecolorallocate($im, 255, 0, 0);
    imagettftext($im, 32, 0, 380, 430, $black, $font, $text);
    imagettftext($im, 52, 0, 630, 530, $black1, $font, $string);
    imagejpeg($im, null, 90);
?>

However, the manual states:-

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.

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

Upvotes: 1

Related Questions