For a design project I am required to have spacing between characters; since imagefttext does not support this feature I have created a function which does support this.
The arguments are identical to imagefttext, accept that (array)$extrainfo now accepts the 'character_spacing' spacing parameter. The return values are as expected, and include the image boundaries of the entire string including the character spacing.
The downside is that $angle rotates each letter instead of rotating the entire word (could be seen as a feature on its own).
I hope this is of some use to someone.
- KeepSake
<?php
// Required header (assuming we use png images)
header("Content-type: image/png");
// Create a basic image with a dark background.
$image = imagecreatetruecolor(300, 20);
imagefill($image, 0, 0, imagecolorallocate($image, 21, 21, 21));
// Function call, arguments are the same as imagefttext, expect that (array)$extrainfo takes a new paramenter called character_spacing.
$imageBox = imagefttext2($image, 9, 0, 2, 15, imagecolorallocate($image, 255, 255, 255), 'tahomabold.ttf', 'The quick brown fox...', array('character_spacing' => 5));
// Output the file, and clear the resources
imagepng($image);
imagedestroy($image);
function imagefttext2($imageResource, $font_size, $text_angle, $start_x, $start_y, $color, $font_file, $text, $extra_info = array()) {
if($extra_info['character_spacing'] == NULL || !is_numeric($extra_info['character_spacing'])) {
$extra_info['character_spacing'] = 0;
}
$lastX = $start_x - $extra_info['character_spacing'];
foreach(str_split($text) as $v) {
$coordinates = imagefttext($imageResource, $font_size, $text_angle, $lastX + $extra_info['character_spacing'], $start_y, $color, $font_file, $v, $extra_info);
$lastX = max($coordinates[2], $coordinates[4]);
}
// Return the newly generated image box coordinates:
return array($start_x, $start_y, $coordinates[2], $coordinates[3], $coordinates[4], $coordinates[5], $start_x, $coordinates[7]);
}
?>
imagefttext
(PHP 4 >= 4.0.7, PHP 5)
imagefttext — Écrit du texte dans une image avec la police courante FreeType 2
Description
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 à utiliser, en nombre de points.
- angle
-
L'angle, en degrés ; 0 degré pour une lecture du texte de gauche à droite. Les grandes valeurs représentent une rotation dans le sens des aiguilles d'une montre. Par exemple, une valeur de 90 aura pour effet de lire le texte du bas vers le haut.
- x
-
Les coordonnées, fournies par x et y définissent le point de départ du premier caractère (et plus précisément, le coin en bas à gauche du caractère). C'est un comportement différent de la fonction imagestring(), où x et y définissent le coin en haut, à gauche du premier caractère. Par exemple, en haut à gauche vaut 0, 0.
- y
-
L'ordonnée y-ordinate. Ce paramètre configure la position de base de la police, et non pas le bas de cette dernière.
- color
-
L'index de la couleur désirée pour le texte, voir la fonction imagecolorexact().
- fontfile
-
Le chemin vers la police TrueType à utiliser.
Suivant la version de GD utilisée par PHP, il sera recherché les fichiers qui ne commencent pas par un '/', en y ajoutant l'extension '.ttf', et suivant le chemin des polices défini par la bibliothèque.
Lors de l'utilisation d'une version de GD inférieure à 2.0.18, un caractère d'espacement (plutôt qu'un point-virgule) était utilisé comment séparateur dans le chemin pour les différents fichiers de police. Si vous utilisez toujours cette notation, vous obtiendrez le message d'erreur suivant : Warning: Could not find/open font. Pour ces anciennes versions, la seule solution est de déplacer la police dans un dossier qui ne contient pas d'espace.
Dans la plupart des cas, lorsque la police se trouve dans le même dossier que le script qui cherche à l'utiliser, la solution suivante permet de s'affranchir de tous les problèmes relatifs à l'inclusion.
<?php
// Définit la variable d'environnement pour GD
putenv('GDFONTPATH=' . realpath('.'));
// Nom de la police à utiliser (note qu'il n'y a pas d'extension .ttf)
$font = 'SomeFont';
?> - text
-
Le texte à insérer dans l'image.
- extrainfo
-
Indexes possibles pour le tableau extrainfo Clé Type Signification linespacing float Définit l'espacement entre les lignes lors du dessin
Valeurs de retour
Cette fonction retourne un tableau définissant les 4 points d'une boîte, en commençant par le coin en bas, à gauche, puis, les suivants, dans le sens des aiguilles d'une montre :
| 0 | x : coordonnée en bas, à gauche |
| 1 | y : coordonnée en bas, à gauche |
| 2 | x : coordonnée en haut, à droite |
| 3 | y : coordonnée en bas, à droite |
| 4 | x : coordonnée en haut, à droite |
| 5 | y : coordonnée en haut, à droite |
| 6 | x : coordonnée en haut, à gauche |
| 7 | y : coordonnée en haut, à gauche |
Exemples
Exemple #1 Exemple avec imagefttext()
<?php
// Création d'une image de 300x100 pixels
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
// Définit l'arrière-plan en rouge
imagefilledrectangle($im, 0, 0, 299, 99, $red);
// Chemin vers notre fichier de police ttf
$font_file = './arial.ttf';
// Dessine le texte 'PHP Manual' en utilisant une police de taille 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');
// Affichage de l'image sur le navigateur
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
Notes
Note: Cette fonction requiert la bibliothèque GD 2.0.1 ou supérieure (2.0.28 ou supérieure est recommandée).
Note: Cette fonction n'est disponible que si si PHP est compilé avec le support Freetype (--with-freetype-dir=DIR)
Historique
| Version | Description |
|---|---|
| 4.3.5 | Le paramètre extrainfo est devenu optionnel. |
imagefttext
17-Sep-2009 06:05
24-Nov-2007 07:26
realpath(".")
realpath(getenv("SCRIPT_FILENAME"));
could be different. This helped when setting GDFONTPATH.
29-Mar-2007 11:58
I had trouble working out how to accurately represent fonts in point sizes when constructing charts that had a user-customisable output DPI (basically, the user could specify the size of the chart in mm - or any other physical measure - and the DPI to create arbitrarily-sized charts to work properly in real printed documents).
GD1 was OK as it used pixels for font rendering, but GD2 uses points, which only makes any sense if you know the DPI that it assumes when rendering text on the image surface. I have not been able to find this anywhere in this documentation but have examined the GD2 source code and it appears to assume a DPI of 96 internally. However, this can easily be customised in the GD2 source so it cannot be assumed that all PHP interpreters out there have a GD2 compiled using 96dpi internally.
If it does, and you are using it to construct images whose target DPI is not 96, you can calculate the point size to supply to imageftbox() and imagefttext() like this:
<?php
/* 100mm x 100mm image */
$imageWidth = 100;
$imageHeight = 100;
/* 300 dpi image, therefore image is 1181 x 1181 pixels */
$imageDPI = 300;
/* unless we do this, text will be about 3 times too small */
$realFontSize = ($fontPt * $targetDPI) / 96;
?>
09-Nov-2006 10:53
Since this function is not documented, I felt it was best that I shed some light on the extrainfo parameter.
You can see the full documentation at the GD reference manual:
http://www.boutell.com/gd/manual2.0.33.html#gdImageStringFTEx
Basically it accepts an array containing the following options as keys and an associated value:
(int) flags [more info in the GD reference manual]
(double/float) linespacing
(int) charmap
(int) hdpi
(int) vdpi
(string) xshow
(string) fontpath
My C/C++ is not very good but this is the best I can explain. Read the documentation for more information. :-)
A very simple example of usage would be:
<?php
imagefttext( $img_pointer, 12, 0, 10, 10, [-insertsomecolour-], '/path/to/font.ttf', "THIS IS A TEST\nTHIS IS LINE 2\nTHIS IS LINE3", array('lineheight'=>2.0) );
?>
I am using php 5.1.2 on a winxp machine. I was getting into the TrueType fonts and wanted to see which ones would look best incorporated into web images. So I created the following script that prints out samples of all the TrueType fonts found in my C:\Windows\Fonts directory. The script takes only one request parameter - 'fsize'. It stands for font-size and lets you see each font in any size you wish -- I limited it to values between 5 and 48. Hope this helps someone other than me :)
I apologize in advance if any of my code is not the prettiest-written php code even seen -- I have only been coding in php for the past week (I'm a perl-guy usually).
<?php
list($x, $y, $maxwidth) = array(0, 0, 0);
$fsize = (int)$_REQUEST['fsize'];
if ($fsize < 5 or $fsize > 48) $fsize = 8;
header("Content-type: image/jpeg");
// don't know how wide or tall the font samples will be.
// create a huge image for now, we'll copy it smaller
// later when we know how large the image needs to be.
$im = imagecreate(1000, 20000) or die('could not create!');
$clr_white = imagecolorallocate($im, 255, 255, 255);
$clr_black = imagecolorallocate($im, 0, 0, 0);
$font_path = "C:/Windows/Fonts/";
$dh = opendir($font_path);
while (($file = readdir($dh)) !== FALSE) {
// we're only dealing with TTY fonts here.
if (substr(strtolower($file), -4) != '.ttf') continue;
$str = "Sample text for '$file'";
$bbox = imagettfbbox(
$fsize, 0, "{$font_path}{$file}", $str
);
$ww = $bbox[4] - $bbox[6];
$hh = $bbox[1] - $bbox[7];
imagettftext(
$im, $fsize, 0, $x, $y,
$clr_black, "{$font_path}{$file}", $str
);
$y += $hh + 20;
if ($ww > $maxwidth) $maxwidth = $ww;
}
closedir($dh);
// ok, now we can chop off the extra space from the
// 1000 x 20000 image.
$im2 = imagecreate($maxwidth + 20, $y);
imagecopyresized(
$im2, $im, 0, 0, 0, 0, $maxwidth + 20,
$y, $maxwidth + 20, $y
);
imagejpeg($im2);
imagedestroy($im);
imagedestroy($im2);
?>
23-Nov-2005 06:16
If you want to get the best result in monochrome font rendering, change render_mode to FT_LOAD_RENDER. It's the last parameter of FT_Load_Glyph() function (in gdft.c).
23-Jun-2005 11:25
For negative image you must add one line after the $grayColor computation:
$grayColor = ~ $grayColor & 0x7FFFFFF;
29-May-2005 12:11
This function is very simular to imageffttext(), you may find the information provided on its manual page helpful:
http://php.net/imagettftext
27-Jan-2005 11:20
When compiling PHP with FreeType 2 support, you'll probably have some problems if - for example - you use debian and didn't compile freetype2 yourself...
If configure fails after saying "If configure fails, try --with-xpm-dir..." you most likely have FreeType1 installed, but not freetype2 ...
Do this as root :
apt-get install libfreetype6-dev
It took me some time to find out that apt-get install freetype2 is actually installing freetype1 ...
08-Dec-2004 05:27
I found myself in need of an align right function and found one on the imagepstext manual page. I can't imagine I'm the only person who's needed to use this, so here's a slightly modified version that works with imagefttext:
<?
function align_right($string, $fontfile, $imgwidth, $fontsize){
$spacing = 0;
$line = array("linespacing" => $spacing);
list($lx,$ly,$rx,$ry) = imageftbbox($fontsize,0,$fontfile,$string,$line);
$textwidth = $rx - $lx;
$imw = ($imgwidth-10-$textwidth);
return $imw;
}
?>
24-Jan-2004 11:05
I wrote a bit of code to gather all the .ttf files in the directory with this script, and randomize them to write text on a header image for my site. The only catch is the font files have to be named 1.ttf, 2.ttf etc etc.
<?php
srand((double)microtime()*1234567); // Start the random gizmo
$image = imagecreatefromjpeg(rand(1,exec('ls *.jpg | wc -l')) . ".jpg"); // Get a background
$font = rand(1,exec('ls *.ttf | wc -l')) . ".ttf"; // Get a font
$textcolor = imagecolorallocate($image,0,0,0); // Set text color
$text1 = "shenko.homedns.org"; // Here is our text
imagettftext($image, 50, 0, 20, 50, $textcolor, $font, $text1); // Write the text with a font
header("Content-type: image/jpeg"); // Its a JPEG
imagejpeg($image,'',90); // Zap it to the browser
imagedestroy($image); // Memory Freeupage
?>
17-Sep-2003 11:07
After spending the evening with some work on automatically generated images, I had the idea to switch of anti-aliasing (looking, if some font would look better that way), which turned out not to be quite so easy.
Actually you have to use the negative of the desired color to switch of antialising. I include the corresponding line from my code (line split up):
// USE NEGATIVE OF DESIRED COLOR TO SWITCH OF ANTI-ALIASING
ImageFTText ($neuesBild,$fontsize,$fontangle,$TextPosX,$TextPosY,
-$custom_fg,$fonttype,$text,array());
21-Nov-2002 09:22
Thanks for the script! I modified it to show several fonts that I was wanting to use. I am using GD-2.0.7, FreeType-2.1.3(text rotation fix,among others), and PHP-4.2.3 and had to include the array information to get it to work.
Code change follows:
$fontfile="/usr/local/fonts/ttf/bookantbd.ttf";
// Waterfall of point sizes to see what Freetype 2's autohinting looks like:
//
for($i=4;$i<=12;$i++){
ImageFtText($image,$i,0,10,(280+$i*14),$forecolor,$fontfile, bookantbd . $i . ". " . $string, array("linespacing" => 1.0));
}
John
08-Aug-2002 09:59
If you're interested in turning off FreeType hinting, search for the following line in the gd source (gdft.c):
err = FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT);
and replace it with
err = FT_Load_Glyph (face, glyph_index, FT_LOAD_NO_HINTING);
Recompile GD, and voìla: beauteous antialiasing.
