"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.
imagettftext
(PHP 4, PHP 5)
imagettftext — Dessine un texte avec une police TrueType
Description
Dessine le texte fourni avec une police TrueType.
Liste de paramètres
- image
-
Une ressource d'image, retourné par une des fonctions de création d'images, comme imagecreatetruecolor().
- size
-
La taille de la police. En fonction de la version de votre bibliothèque GD, elle doit être spécifiée en pixels (GD1) ou en points (GD2).
- angle
-
L'angle, en degrés ; 0 degré correspond à la lecture du texte de gauche à droite. Les valeurs positives représentent une rotation dans le sens contraire des aiguilles d'une montre. Par exemple, une valeur de 90 correspondra à une lecture du texte de bas en haut.
- x
-
Les coordonnées données par x et y définiront la position du premier caractère (le coin bas-gauche du caractère). Cela est différent de la fonction imagestring(), où x et y définissent le coin haut-gauche du premier caractère. Par exemple, "haut gauche" correspond à 0, 0.
- y
-
L'ordonnée Y. Cela définit la position de la ligne de base de la police, et non pas le bas des caractères.
- color
-
L'index de la couleur. Utiliser un index de couleur négatif désactivera l'antialiasing. Voir la fonction imagecolorallocate().
- fontfile
-
Le chemin vers la police TrueType que vous souhaitez utiliser.
Dépendant de la version de la bibliothèque GD utilisée par PHP, lorsque fontfile ne commence pas par un caractère / alors .ttf sera ajouté au nom du fichier et la bibliothèque recherchera ce nom de fichier dans les dossiers de police, définis par la bibliothèque.
Lorsque vous utilisez une version de la bibliothèque GD inférieure à 2.0.18, un caractère espace, plutôt qu'un point-virgule, est utilisé pour définir des chemins alternatifs pour les fichiers de police. Si vous utilisez involontairement cette fonctionnalité, vous aurez ce message d'erreur : Warning: Could not find/open font. Pour ces versions affectées, la seule solution est de déplacée la police à un endroit qui ne contient pas d'espaces dans les noms de dossier.
Dans le cas fréquent où une police réside dans le même dossier que le script l'utilisant, l'astuce suivante vous épargnera tous les problèmes.
<?php
// Définition de la variable d'environnement pour GD
putenv('GDFONTPATH=' . realpath('.'));
// Nom de la police à utiliser (notez l'absence de l'extension .ttf)
$font = 'SomeFont';
?> - text
-
La chaîne de texte, en UTF-8.
Peut inclure des références à des caractères numériques, décimales (sous la forme : € ) pour accéder aux caractères d'une police au delà du premier 127. Les chaînes de caractères encodées en UTF-8 peuvent être passées directement.
Les entités nommées, comme ©, ne sont pas supportées. Utilisez la fonction html_entity_decode() pour encoder ces entités nommées en chaîne UTF-8 (la fonction html_entity_decode() supporte ceci depuis PHP 5.0.0.).
Si un caractère est utilisé dans une chaîne qui n'est pas supportée par la police, un rectangle creux remplacera le caractère.
Valeurs de retour
Retourne un tableau de 8 éléments représentant quatre points marquants les limites du texte. L'ordre des points est : inférieur gauche, inférieur droit, supérieur droit, supérieur gauche. Les points sont relatifs au texte par rapport à l'angle, donc, "supérieur gauche" signifie dans le coin en haut à gauche lorsque vous regardez le texte horizontalement.
Exemples
Exemple #1 Exemple avec imagettftext()
Cet exemple produira une image PNG blanche de 400x30 pixels, avec le texte "Test..." en noir, avec une ombre grise, utilisant la police Arial.
<?php
// Définition du content-type
header("Content-type: image/png");
// Création de l'image
$im = imagecreatetruecolor(400, 30);
// Création de quelques couleurs
$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);
// Le texte à dessiner
$text = 'Test...';
// Remplacez le chemin par votre propre chemin de police
$font = 'arial.ttf';
// Ajout d'ombres au texte
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Ajout du texte
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Utiliser imagepng() donnera un texte plus claire,
// comparé à l'utilisation de la fonction imagejpeg()
imagepng($im);
imagedestroy($im);
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
Notes
Note: Cette fonction requiert la bibliothèque GD ainsi que la bibliothèque » FreeType.
imagettftext
03-Oct-2008 05:59
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.
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
?>
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
}
}
?>
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.
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);
?>
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!
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.
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);
}
?>
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
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');
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.
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.
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.
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.
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
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.
)
)
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!
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;
}
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;
}
?>
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);
?>
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;
}
?>
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.
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('€');
$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.
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,