PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

imagetypes> <imagettfbbox
Last updated: Fri, 22 Aug 2008

view this page in

imagettftext

(PHP 4, PHP 5)

imagettftextWrite text to the image using TrueType fonts

Description

array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )

Writes the given text into the image using TrueType fonts.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().

fontfile

The path to the TrueType font you wish to use.

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

text

The text string in UTF-8 encoding.

May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127. The hexadecimal format (like &#xA9;) is supported as of PHP 5.2.0. Strings in UTF-8 encoding can be passed directly.

Named entities, such as &copy;, are not supported. Consider using html_entity_decode() to decode these named entities into UTF-8 strings (html_entity_decode() supports this as of PHP 5.0.0).

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

Return Values

Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally.

Examples

Example #1 imagettftext() example

This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.

<?php
// Set the content-type
header("Content-type: image/png");

// Create the image
$im imagecreatetruecolor(40030);

// Create some colors
$white imagecolorallocate($im255255255);
$grey imagecolorallocate($im128128128);
$black imagecolorallocate($im000);
imagefilledrectangle($im0039929$white);

// The text to draw
$text 'Testing...';
// Replace path by your own font path
$font 'arial.ttf';

// Add some shadow to the text
imagettftext($im2001121$grey$font$text);

// Add the text
imagettftext($im2001020$black$font$text);

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

The above example will output something similar to:

Notes

Note: This function requires both the GD library and the » FreeType library.

See Also



imagetypes> <imagettfbbox
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
imagettftext
s.pynenburg at gmail dot com
07-Aug-2008 11:26
There's an error in that function I just posted - replace the variable

<?PHP
$x_pos1
?>

with simply:

<?PHP
$x_pos
?>
s.pynenburg _at_ gm ail dotcom
07-Aug-2008 10:31
I had an image generator where the user could position where they wanted the text to begin - however it kept going off the side of an image. So I made this basic function: it measures if the inputted text and x-position will cause the string to go off the edge, and if so, it will fit as much as it can on the first line, then go down to the next one.
Limitations:
-It only performs this once (i.e. it won't split into three lines)
-I'm pretty sure it won't work with angled text.

<?PHP

function imagettftextwrap($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr)
{
   
$box = @imagettfbbox($size, 0, $font, $instr);
   
$width = abs($box[4] - $box[0]);
   
$height = abs($box[3] - $box[5]);
   
$overlap = (($x_pos + $width) - imagesx($im));
    if(
$overlap > 0) //if the text doesn't fit on the image
   
{
       
$chars = str_split($instr);
       
$str = "";
       
$pstr = "";
        for(
$m=0; $m < sizeof($chars); $m++)
        {
           
$bo = imagettfbbox($fsize1, 0, $font1, $str);
           
$wid = abs($bo[4] - $bo[0]);
            if((
$x_pos1 + $wid) < imagesx($im)) //add one char from the string as long as it's not overflowing
           
{
               
$pstr .= $chars[$m];
               
$bo2 = imagettfbbox($fsize1, 0, $font1, $pstr);
               
$wid2 = abs($bo2[4] - $bo2[0]);
                if((
$x_pos1 + $wid2) < imagesx($im))
                {
                   
$str .= $chars[$m];
                }   
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
       
$restof = "";
        for(
$l=$m; $l < sizeof($chars); $l++)
        {
           
$restof .= $chars[$l]; //add the rest of the string to a new line
       
}
       
imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $str); // print out the smaller line
       
imagettftext($im, $size, $angle, 0, $y_pos + $height, $color, $font, $restof); //and the rest of it
   
}
    else
    {
       
imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr); //otherwise just do normally
   
}

}

?>
sk89q
01-Aug-2008 04:03
I updated my imagettftextbox function considerably. It fixes the problems of the older imagettftextbox code I uploaded a few months ago (that's now gone).

You can get it here:
http://sk89q.therisenrealm.com/2008/08/ttf-textbox-in-php/

It has both horizontal and vertical alignment, custom line spacing, borders, width, height, etc.
Stefan at colulus dot com
20-May-2008 01:40
I worked out a script the allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print
"Image $next:<br>";
print
"<img src = 'Image.php?\$text=$next'>";
print
"<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagepng($im);

?>
Valentijn de Pagter
16-May-2008 01:13
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb
= imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x
= ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
damititi at gmail dot com
22-Apr-2008 04:21
First of all, thanks sk89q for the func! it was exactly I was looking for.

I made a change. Depending on the letter, the text were incorrect vertical aligned.
I replace the line:
                $line_height = $dimensions[1] - $dimensions[7];
for the following:
                $line_height = $size+4;

No matter if mama or jeje is written, the vertical position will be the same.
sk89q
14-Mar-2008 07:36
Here is an update to my imagettftextwrapped function. I had posted the old version that cut off lines if it wordwrapped.

Here's a new version with the bug fixed, a list of arguments closer to imagettftext(), and partial angle support (the text is angled, but the left margins for each line are not adjusted for the angle).

It's a function I wrote a few years ago to do unjustified aligned text.

<?php
define
("ALIGN_LEFT", "left");
define("ALIGN_CENTER", "center");
define("ALIGN_RIGHT", "right");

function
imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width)
{
       
$text_lines = explode("\n", $text); // Supports manual line breaks!
       
       
$lines = array();
       
$line_widths = array();
       
       
$largest_line_height = 0;
       
        foreach(
$text_lines as $block)
        {
           
$current_line = ''; // Reset current line
           
           
$words = explode(' ', $block); // Split the text into an array of single words
           
           
$first_word = TRUE;
           
           
$last_width = 0;
           
            for(
$i = 0; $i < count($words); $i++)
            {
               
$item = $words[$i];
               
$dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item);
               
$line_width = $dimensions[2] - $dimensions[0];
               
$line_height = $dimensions[1] - $dimensions[7];
               
                if(
$line_height > $largest_line_height) $largest_line_height = $line_height;
               
                if(
$line_width > $max_width && !$first_word)
                {
                   
$lines[] = $current_line;
                   
                   
$line_widths[] = $last_width ? $last_width : $line_width;
                   
                   
/*if($i == count($words))
                    {
                        continue;
                    }*/
                   
                   
$current_line = $item;
                }
                else
                {
                   
$current_line .= ($first_word ? '' : ' ') . $item;
                }
               
                if(
$i == count($words) - 1)
                {
                   
$lines[] = $current_line;
                   
                   
$line_widths[] = $line_width;
                }
               
               
$last_width = $line_width;
                   
               
$first_word = FALSE;
            }
           
            if(
$current_line)
            {
               
$current_line = $item;
            }
        }
       
       
$i = 0;
        foreach(
$lines as $line)
        {
            if(
$align == ALIGN_CENTER)
            {
               
$left_offset = ($max_width - $line_widths[$i]) / 2;
            }
            elseif(
$align == ALIGN_RIGHT)
            {
               
$left_offset = ($max_width - $line_widths[$i]);
            }
           
imagettftext($image, $size, $angle, $left + $left_offset, $top + $largest_line_height + ($largest_line_height * $i), $color, $font, $line);
           
$i++;
        }
       
        return
$largest_line_height * count($lines);
}
?>
llewellyntd at gmail dot com
12-Mar-2008 07:27
Hi All,

I struggled for moths to do a decent text warp with GD lib. Here is the code that I made use of:

<?php
//word wrap
$warpText = wordwrap($text, 30, "\n");
//display text
imagettftext($image, $fontSize, 0, $x, $y, $fontColor, $font, $warpText);
?>

Hope this helps somebody.

Cheers
m0r1arty at mail dot ru
13-Feb-2008 01:50
Sorry my English.
I have trouble with using imagettftext under Windows.
I can't used short name of fonts(example "arial","arialbd.ttf" etc). PHP say what not find this font.
Manipulation with environment GDFONTPATH lost.
This is my solution
<?php
$dir
=opendir('./font/');//directory with fonts
if($dir)
    while(
$f=readdir($dir)){
        if(
preg_match('/\.ttf$/',$f)){
           
$font=explode('.',$f);
           
define($font[0],realpath('./font/'.$f));
        }
    }
if(
$dir)
   
closedir($dir);
?>
Directory "font" have two file: arial.ttf and arialbd.ttf
Now one can using constant font name by calling imagettftext:
imagettftext($img,12,0,25,28,$color,arialbd,'some text');
matt at mmkennedy dot net
17-Jan-2008 10:11
For anyone attempting to print black barcodes, and trying to turn of anti-aliasing, remember that -1 * [0,0,0] is 0, not -0.
denis at reddodo dot com
24-Dec-2007 09:05
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
   
function ttfWordWrappedText_fixed($text, $strlen = 8) {
   
$text = urldecode($text);
   
$text = explode("\n", $text);
   
$i = 0;
    foreach(
$text as $text)
    {
        while(
strlen($text) > $strlen  && strstr($text, ' ') !== FALSE) {
          
$startPoint = strpos($text, ' ');
          
$line[$i][] =substr($text,0,$startPoint); 
          
$text = trim(strstr($text, ' '));
        }
       
$line[$i][] = trim($text);
        }
       
$line[$i][] = trim($text);
       
$i++;
    }
  
    return
$line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
denis at reddodo dot com
24-Dec-2007 08:46
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
   
function ttfWordWrappedText_fixed($text, $strlen = 8) {
   
$text = urldecode($text);
   
$text = explode("\n", $text);
  
   
$i = 0;
    foreach(
$text as $text)
    {
        while(
strlen($text) > $strlen && stristr($text, ' ') !== FALSE) {
          
$startPoint = $strlen - 1;
           while(
substr($text, $startPoint, 1) != " ") {
               
$startPoint--;
           }
          
$line[$i][] = trim(substr($text, 0, $startPoint));
          
$text = substr($text, $startPoint);
        }
       
$line[$i][] = trim($text);
       
$i++;
    }
  
    return
$line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
dotpointer
09-Dec-2007 07:40
For those trying to disable the font smoothing or font cleartype:ing, take a look at the color parameter for this function. The correct word for what you're looking for is antialiasing.
Anonymous
16-Nov-2007 07:14
Just to comment on Sohel Taslims great function...
if anyone needs to add BACKGROUND TRANSPARENCY to this kind of function (which almost does everyone one would want already) then add

$bg_color = imagecolorat($im,1,1);
imagecolortransparent($im, $bg_color);

ABOVE the "if($L_R_C == 0){ //Justify Left"  line
waage
07-Nov-2007 10:31
I had some issues trying to get both word wrapping and new line detection but with some of the help from the comments below i got this. (thanks to jwe for the main part of the code here)

<?php
function ttfWordWrappedText($text, $strlen = 38) {
   
$text = urldecode($text);
   
$text = explode("\n", $text);
   
   
$i = 0;
    foreach(
$text as $text)
    {
        while(
strlen($text) > $strlen) {
          
$startPoint = $strlen - 1;
           while(
substr($text, $startPoint, 1) != " ") {
               
$startPoint--;
           }
          
$line[$i][] = trim(substr($text, 0, $startPoint));
          
$text = substr($text, $startPoint);
        }
       
$line[$i][] = trim($text);
       
$i++;
    }
   
    return
$line;
}
?>

This returns an array for each newline entered and subarray for each wordwrapped line to print.

ie.

Array
(
    [0] => Array
        (
            [0] => This is the first long line
            [1] => that i entered.
        )

    [1] => Array
        (
            [0] => And this is the new line after that.
        )
)
mitch at electricpulp dot com
20-Sep-2007 10:35
If you're having issues with fonts not working... (Could not find/open font) check your permissions on the folder/font files and make sure they're 775, especially if you've just pulled them from a windows box. Hope this helps!
Ole Clausen
11-Sep-2007 12:11
Comment to: Sohel Taslim (03-Aug-2007 06:19)

Thanks for the function which I have modified a bit. In the new version the lines have equal space between them (the g's in your example create bigger space between the lines) - set by the parameter '$Leading'.

I have used the for-loop for better performance and slimmed the rest a little  :)

    /**
     * @name                    : makeImageF
     *
     * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
     *
     * @param String $text     : String to convert into the Image.
     * @param String $font     : Font name of the text. Kip font file in same folder.
     * @param int    $Justify  : Justify text in image (0-Left, 1-Right, 2-Center).
     * @param int    $Leading  : Space between lines.
     * @param int    $W        : Width of the Image.
     * @param int    $H        : Hight of the Image.
     * @param int    $X        : x-coordinate of the text into the image.
     * @param int    $Y        : y-coordinate of the text into the image.
     * @param int    $fsize    : Font size of text.
     * @param array  $color    : RGB color array for text color.
     * @param array  $bgcolor  : RGB color array for background.
     *
     */
    function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){
       
        $angle = 0;
        $_bx = imageTTFBbox($fsize,0,$font,$text);
        $s = split("[\n]+", $text);  // Array of lines
        $nL = count($s);  // Number of lines
        $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    // If Width not initialized by programmer then it will detect and assign perfect width.
        $H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H;    // If Height not initialized by programmer then it will detect and assign perfect height.
       
        $im = @imagecreate($W, $H)
            or die("Cannot Initialize new GD image stream");
       
        $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);  // RGB color background.
        $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); // RGB color text.
       
        if ($Justify == 0){ //Justify Left
            imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
        } else {
            // Create alpha-nummeric string with all international characters - both upper- and lowercase
            $alpha = range("a", "z");
            $alpha = $alpha.strtoupper($alpha).range(0, 9);
            // Use the string to determine the height of a line
            $_b = imageTTFBbox($fsize,0,$font,$alpha);
            $_H = abs($_b[5]-$_b[3]);
            $__H=0;
            for ($i=0; $i<$nL; $i++) {
                $_b = imageTTFBbox($fsize,0,$font,$s[$i]);
                $_W = abs($_b[2]-$_b[0]);
                //Defining the X coordinate.
                if ($Justify == 1) $_X = $W-$_W;  // Justify Right
                else $_X = abs($W/2)-abs($_W/2);  // Justify Center
               
                //Defining the Y coordinate.
                $__H += $_H;
                imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $s[$i]);
                $__H += $Leading;
            }
        }
       
        return $im;
    }
Sohel Taslim
03-Aug-2007 12:19
Left Right Center align/justify of text in image. It is easy and simple to do in PHP.
Create an image from text and align them as you want. After that save or display image.

<?php
/**
 * Function for converting Text to Image.
 * Kip CENTURY.TTF file in same folder.
 *
 * @author Taslim Mazumder Sohel
 * @deprecated 1.0 - 2007/08/03
 *
 */
     //Example call.
   
$str = "New life in programming.\nNext Line of Image.\nLine Number 3\n" .
       
"This is line numbet 4\nLine number 5\nYou can write as you want.";   
   
header("Content-type: image/gif");   
   
imagegif(imagettfJustifytext($str,"CENTURY.TTF",2));
   
//End of example.
   
   
    /**
     * @name                    : makeImageF
     *
     * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
     *
     * @param String $text     : String to convert into the Image.
     * @param String $font     : Font name of the text. Kip font file in same folder.
     * @param int    $W        : Width of the Image.
     * @param int    $H        : Hight of the Image.
     * @param int    $X        : x-coordinate of the text into the image.
     * @param int    $Y        : y-coordinate of the text into the image.
     * @param int    $fsize    : Font size of text.
     * @param array  $color       : RGB color array for text color.
     * @param array  $bgcolor  : RGB color array for background.
     *
     */
   
function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){
       
       
$angle = 0;
       
$L_R_C = $Justify;
       
$_bx = imageTTFBbox($fsize,0,$font,$text);

       
$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    //If Height not initialized by programmer then it will detect and assign perfect height.
       
$H = ($H==0)?abs($_bx[5]-$_bx[3]):$H;    //If Width not initialized by programmer then it will detect and assign perfect width.

       
$im = @imagecreate($W, $H)
            or die(
"Cannot Initialize new GD image stream");
           
           
       
$background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
       
$text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.
       
       
if($L_R_C == 0){ //Justify Left
           
           
imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
           
        }elseif(
$L_R_C == 1){ //Justify Right
           
$s = split("[\n]+", $text);
           
$__H=0;
           
            foreach(
$s as $key=>$val){
           
               
$_b = imageTTFBbox($fsize,0,$font,$val);
               
$_W = abs($_b[2]-$_b[0]);
               
//Defining the X coordinate.
               
$_X = $W-$_W;
               
//Defining the Y coordinate.
               
$_H = abs($_b[5]-$_b[3]); 
               
$__H += $_H;             
               
imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);   
               
$__H += 6;
               
            }
           
        }
        elseif(
$L_R_C == 2){ //Justify Center
           
           
$s = split("[\n]+", $text);
           
$__H=0;
           
            foreach(
$s as $key=>$val){
           
               
$_b = imageTTFBbox($fsize,0,$font,$val);
               
$_W = abs($_b[2]-$_b[0]);
               
//Defining the X coordinate.
               
$_X = abs($W/2)-abs($_W/2);
               
//Defining the Y coordinate.
               
$_H = abs($_b[5]-$_b[3]); 
               
$__H += $_H;             
               
imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);   
               
$__H += 6;
               
            }
           
        }       
                       
        return
$im;
       
    }
       
 
?>
Borgso
27-Jul-2007 07:30
Right align out of "webmaster at higher-designs dot com" code
<?php
$color
= imagecolorallocate($im, 0, 0, 0);
$font = 'visitor.ttf';
$fontsize = "12";
$fontangle = "0";
$imagewidth = imagesx($im);
$imageheight = imagesy($im);

$text = "My right align text";

$box = @imageTTFBbox($fontsize,$fontangle,$font,$text);
$textwidth = abs($box[4] - $box[0]);
$textheight = abs($box[5] - $box[1]);
$xcord = $imagewidth - ($textwidth)-2; // 2 = some space from right side.
$ycord = ($imageheight/2)+($textheight/2);

ImageTTFText ($im, $fontsize, $fontangle, $xcord, $ycord, $black, $font, $text);
?>
Lassial at the google mail dot com
13-Jun-2007 03:42
Creating multiline text with GD is bit complicated, one of the issues I've ran to is how to set line spacing, a normal feature in all type setting (even type writers). By default, line spacing with imagettftext seems to be 150 % or more, too much for me anyhow. Thus I've used the function below to get the lines closer to each other. By default, it appears to create 100 % linespacing, but it has not been tested thoroughly.

null imagettfmultilinetext
(resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text , $spacing)

spacing is a coefficient, comparable to Line spacing in a word processors or graphics software, causing a shift relative to font size in the line spacing

<?php
function imagettfmultilinetext($image, $size, $angle, $x, $y, $color, $fontfile$text, $spacing=1)
{

$lines=explode("\n",$text);
for(
$i=0; $i< count($lines); $i++)
    {
   
$newY=$y+($i * $size * $spacing);
   
imagettftext($image, $size, $angle, $x, $newY, $color, $fontfile$lines[$i], $spacing);
    }
return
null;
}
?>
ken at smallbox software
11-Jun-2007 12:24
Strangely this function seems to work with adobe post script files (tried .pfb) not sure why this isn't documented or why there is a separate set of functions for dealing with postscript.
php at gilbertson dot me dot uk
01-Jun-2007 04:52
Users may note a problem trying to use this function to display the Euro symbol.

The reason is that it is a late addition. Although the operating systems generally recognise code 0x80 (128 decimal) as Euro, this is not where it necessarily appears in the font. Some have it there, but many just have it in the extended character set at position 0x20AC (8364 decimal).

I have yet to find a font with it only at 0x80, so here is the fix:

<?php
$image
=imagecreate(135,24);
$bg=imagecolorallocate($image,0,0,0);
$fg=imagecolorallocate($image,0,255,0);
$text = 'coffee - €3.50';
$friendly = eurofix($text);
imagettftext($image,16,0,5,20,$fg,"Papyrus.ttf",$friendly);
imagegif ($image);
imagedestroy ($image);

function
eurofix($str) {
$euro=utf8_encode('&#8364;');
$str = preg_replace('/\x80/',$euro,$str);
return (
$str);
}
?>

You should note, however, this won't help with fonts older than about 1999. It can only make sure the Euro is displayed where available.
lassial at gmail dot com
10-May-2007 09:56
Roy van Arem suggested a neat code for listing TTFs on a machine. However, it has some problems (such as lower and upper case distinction of file extension and defective fonts) that I have corrected in the following script, which can be implemented as a single PHP script (name as you like):

<?php //make sure there are no blank lines above
       
$ffolder="/usr/local/bin/fonts"; //The directory where your fonts reside

if (empty($_GET['f']))
{
$folder=dir($ffolder); //open directory
echo "<HTML><BODY>\n";
   
while(
$font=$folder->read())
  if(
stristr($font,'.ttf')) //only ttf fonts
       
$fonts[]=$font;
       
$folder->close();

if (!empty(
$fonts))
        {
        echo
"<table><tr><th colspan='2'>Fonts available in $ffolder</th></tr>"
       
."\n<tr><th>Name</th><th>Appereance</th>";
       
sort($fonts);
        foreach (
$fonts as $font)
                echo
"<tr><td>$font</td><td> <IMG src='".$_SERVER['SCRIPT_NAME']
                        .
"?f=$font'></td></tr>\n";
        }
else echo
"No fonts found from $ffolder";
echo
"\n</HTML></BODY>";
}

else
{
$im=@imagecreatetruecolor(200,30)
        or die(
"Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0