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)

imagettftextEscribir un texto sobre la imagen usando fuentes TrueType

Descripción

array imagettftext ( resource $imagen , float $tamanyo , float $angulo , int $x , int $y , int $color , string $archivo_fuente , string $texto )

Escribe el texto dado en la imagen usando fuentes TrueType.

Lista de parámetros

image

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

tamanyo

El tamaño de la fuente. Dependiendo de su versión de GD, éste puede ser especificado como el tamaño en píxeles (GD1), o el tamaño en puntos (GD2)

angulo

El ángulo en grados, en donde 0 grados significa texto de lectura de izquierda-a-derecha. Valores más altos representan una rotación en sentido contrario al de las manecillas del reloj. Por ejemplo, un valor de 90 resulta en texto de lectura de abajo-hacia-arriba.

x

Las coordenadas dadas por x y y definirán el punto base del primer caracter (a grandes rasgos la esquina inferior izquierda del caracter). Esto a diferencia de imagestring(), en donde x y y definen la esquina superior izquierda del primer caracter. Por ejemplo, "arriba a la izquierda" es 0, 0.

y

La coordenada y. Ésta establece la posición de la línea base de las fuentes, no la parte más baja del caracter.

color

El índice de color. Usar un índice de color negativo tiene el efecto de deshabilitar el anti-alias. Vea imagecolorallocate()

archivo_fuente

La ruta a la fuente TrueType que desea usar.

Dependiendo de la versión de la biblioteca GD que usa PHP, cuando archivo_fuente no comienza con / entonces .ttf se añade al nombre de archivo y la biblioteca intentará buscar ese archivo a lo largo de una ruta de fuentes definida en la biblioteca.

Cuando se usan versiones de la biblioteca GD inferiores a 2.0.18, un caracter de espacio, en lugar de un punto-y-coma, era usado como el 'separador de ruta' para diferentes archivos de fuente. El uso no intencionado de esta característica resulta en el mensaje de advertencia: Warning: Could not find/open font. Para estas versiones afectadas, la única solución es mover la fuente a una ruta que no contenga espacios.

En muchos casos en los que una fuente reside en el mismo directorio que el script que la utiliza, el siguiente truco aliviará los problemas de inclusión.

<?php
// Definir la variable de entorno para GD
putenv('GDFONTPATH=' realpath('.'));

// Nombre de la fuente a usar (note la falta de la extensión .ttf)
$fuente 'AlgunaFuente';
?>

texto

La cadena de texto en codificación UTF-8.

Puede incluir referencias numéricas de caracter (de la forma: &#8364;) para acceder a caracteres en una fuente más allá de la posición 127. El formato hexadecimal (como &#xA9;) es soportado a partir de PHP 5.2.0. Es posible pasar cadenas en codificación UTF-8 directamente.

Las entidades con nombre, como &copy;, no son soportadas. Considere usar html_entity_decode() para decodificar tales entidades a cadenas UTF-8 (html_entity_decode() soporta esta aplicación a partir de PHP 5.0.0).

Si un caracter que no es soportado por la fuente es usado en la cadena, un rectángulo vacío reemplazará al caracter.

Valores retornados

Devuelve una matriz con 8 elementos que representan cuatro puntos que forman la caja circundante del texto. El orden de los puntos es inferior izquierdo, inferior derecho, superior derecho y superior izquierdo. Los puntos son relativos al texto independientemente del ángulo, así que "superior izquierdo" quiere decir la esquina del lado superior izquierdo cuando ve el texto horizontalmente.

Ejemplos

Example #1 Ejemplo de imagettftext()

Este script de ejemplo producirá un PNG blanco de 400x30 pixeles, con las palabras "Probando..." en negro (con sombra gris), en la fuente Arial.

<?php
// Establecer el tipo de contenido
header("Content-type: image/png");

// Crear la imagen
$im imagecreatetruecolor(40030);

// Crear algunos colores
$blanco imagecolorallocate($im255255255);
$gris   imagecolorallocate($im128128128);
$negro  imagecolorallocate($im000);
imagefilledrectangle($im0039929$blanco);

// El texto a pintar
$texto 'Probando...';
// Reemplaze la ruta con su propia ruta a la fuente
$fuente 'arial.ttf';

// Agregar una sombra al texto
imagettftext($im2001121$gris$fuente$texto);

// Agregar el texto
imagettftext($im2001020$negro$fuente$texto);

// Usar imagepng() resulta en texto más claro, en comparación con imagejpeg()
imagepng($im);
imagedestroy($im);
?>

El resultado del ejemplo seria algo similar a:

Notes

Note: Esta función requiere tanto la biblioteca GD como la biblioteca » FreeType.

Ver también



imagetypes> <imagettfbbox
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
imagettftext
cameron at prolifique dot com
03-Oct-2008 05:59
"php at yvanrodrigues dot com" is right...this function is not reliable on extended characters. User beware.

In my case, it produced different results with OpenType vs. TrueType versions of the same font. (Converted my OT font to TT using FontForge as suggested. Strangely, the resulting TT font file was twice as big as the OT version and didn't look the same...heavier weight and slightly different spacing.) While the TT version was more accurate at displaying certain characters, neither was totally reliable, both yielding boxes in place of perfectly valid character glyphs that I could verify existed in the font. (Both fonts showed the same characters perfectly on an HTML page with UTF-8 charset.)

What's more, using this same function with the same font on our development vs. production server also produced different results: some chars worked on dev but not production. Stranger still, the font spacing and size were slightly different between the two. Font file is identical. Dev server is Linux, production server is Windows, but should that matter? Suspect it has more to do with differing versions of FreeType (2.1 vs. 1.9 respectively).

Anyway, careful with this function...best to stick within the rather small range of safe characters and avoid anything else.
php at yvanrodrigues dot com
05-Sep-2008 04:10
After many hours of failure may I suggest:

This function will work on OpenType fonts with Postscript outlines, but from what I can tell, characters > ASCII 127 do not display correctly or at all, even if the text is correctly coded as UTF-8.

Converting the font to truetype or possibly OpenType with truetype outlines; or buying the font as such fixes the problem.

I used FontForge to open the otf and export as ttf and it works perfectly.
s.pynenburg at gmail dot com
07-Aug-2008 05: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 04: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 10: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 07: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 07: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 10: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
15-Mar-2008 12: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 12: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 07: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
18-Jan-2008 04: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 03: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 02: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 01: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 01: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 04: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 04: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 06: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 06: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
28-Jul-2007 01: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 09: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 06: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 10: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 03: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,