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 GDputenv('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.
Strings in UTF-8 encoding can be passed directly.

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

Valori restituiti

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.
Returns FALSE on error.

Log delle modifiche

Versione

Descrizione

5.2.0

It is now possible to specify an hexadecimal entity in
text.

Esempi

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.

Vedere anche:

User Contributed Notes 58 notes

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.

For your general edification: The following drop-in function will place a block of fully justified text onto a GD image. It is a little CPU heavy, so I suggest caching the output rather than doing it on-the-fly.

Arguments:

$image - the GD handle of the target canvas $size - text size $angle - slope of text (does not work very well), leave at 0 for horizontal text $left - no. of pixels from left to start block $top - no. of pixels from top to start block $color - handle for colour (imagecolorallocate result) $font - path to .ttf font $text - the text to wrap and justify $max_width - the width of the text block within which the text should be wrapped and fully justified $minspacing - the minimum number of pixels between words $linespacing - a multiplier of line height (1 for normal spacing; 1.5 for line-and-a-half etc.)

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!

Just in case you were--like me--unaware of this, in Windows, ttf fonts don't necessarily antialias at all font sizes. Arial appears to work at all sizes but Calibri, for example, only antialiases at a point size of 8 and then at all sizes 16 and up. Not only that but at fonts sizes like 10 and 12 characters don't print at the expected angle: the characters are all printed upright on an angled baseline.

I was having trouble trying to render non antialiased text using a pixel font. The tips about setting a negative value for the color are valid, but I was still having trouble with the text I was trying to render because it was black. I discovered that if I changed the imagecolorallocate() function from:

$color = imagecolorallocate($base, 0, 0, 0);

to

$color = imagecolorallocate($base, 1, 1, 1); (near black)

and then used the negative value for the color in imagettftext(), it would work properly. The difference is that my first implementation set $color = 0. Obviously, you can't have $color = -0, it made no difference. When I switched to (1,1,1) it became $color = 1 which I could take a negative value for.

Note that imagettftext and imagettfbbox will keep file handles open for fonts used (at least in Windows, Apache 2, PHP 5.3.24) - there is a bug report on that but it's related to FreeType, so if you load several types of fonts, or temporary fonts, you may find your system reaching max handles open. Also, you won't be able to unlink it or remove folders that contain the font.

// retrieve boundingbox of the rotated text $bbox = imagettfbbox($size, $angle, $fontfile, $text); //calculate the parameters of the line from lowerleft to upperright point $m1 = ($bbox[5]-$bbox[1])/($bbox[4]-$bbox[0]); $q1 = $bbox[1]-($bbox[0]*$m1); //calculate the parameters of the line from upperleft to lowerright point $m2 = ($bbox[3]-$bbox[7])/($bbox[2]-$bbox[6]); $q2 = $bbox[7]-($bbox[6]*$m2); //calculate the rectangle center (intersection of the two lines) $nx = ($q1-$q2)/($m2-$m1); $ny = ($m1*($q1-$q2)/($m2-$m1))+$q1;

"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.

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 :)

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).

//setting the image header in order to proper display the imageheader("Content-Type: image/png");//try to create an image$im = @imagecreate(460, 215) or die("Cannot Initialize new GD image stream");//set the background color of the image$background_color = imagecolorallocate($im, 0x00, 0x00, 0x00);//set the color for the text$text_color = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);//adf the string to the image

Quick tip for anyone who is receiving text like in the example in this page (ie: through $_GET['text'] or something similar) and needs to format the text into multiple lines. The trick is finding the spaces...

The result is an array called $line that contains all the lines of text you need to output in order.

The only tasks left are to determine the correct height of the image based on the font size you want to use. Don't forget to leave some padding space for punctuation and descenders between lines (commas, g, q, p, y, etc).

imagettftext is unbelievably useful when you need to create header images using non-standard fonts. Amazing. Huge thanks to the devs.

Hi all!When my hoster updated his php's libs at first minutes i've got the same problem as some of you.Php couldn't find the path to true type fonts.The solution in my case was to make the path look like this<?phpimagettftext($im, 20, 0, 620, 260, $secondary_color, "./tahoma.ttf" , "NEWS");?>so as you can see i simply added "./"

another tip that i wanted to add here is how to write in RUssian on image using imagettftextyou simply have to change the function argument like this<?phpimagettftext($im, 15, 0, 575, 300, $secondary_color, "./tahoma.ttf" , win2uni("some word in russian"));?>where win2uni is the function that converts win1251 to unicode. here is the code of it<?php

If you are getting all rectangles instead of text, it may well mean that your ttf font is not opentype, particularly if it is an older freeware one. This requirement didn't exist in older versions so you may find that your font stops working after you upgrade. To fix this problem, try downloading the free MS Volt utility. From there, open your font file, and then click on Compile, and resave.

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.

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:<?phpfunction ttfWordWrappedText_fixed($text, $strlen = 8) {$text = urldecode($text);$text = explode("\n", $text);

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):

I have found the kerning (spacing between letters) pretty poor with GD - it's not up to your average designer's standards. Here are some ways to improve it:- Place the letters one by one using their bounding box instead of using one string- adjust with a $kerning value- For small text, sample it down from a larger size to adjust in increments less than 1px

"May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127."

I was using a font that had apostrophes and quotes stored in a non-standard position, and so they were being rendered as spaces by imagettftext. This line seemed to suggest a solution, but it took a while to figure it out.

Turns out, a "decimal numeric character reference" is a decimal conversion of the hex value of the *unicode* position of the character you want. For a while I was trying ASCII positions (I knew the ALT+ code for typing the character I needed in Windows).

In the Windows XP character map, the unicode positions are shown as U+2018 or U+201C, etc. Ignore the U+ and convert that hex number to decimal, and then stick that in your text string with the &# on the front and ; on the end, and pass it to imagettftext.

I was looking for a way to add kerning to my text and finally just made this function to do it. Of course, if you're generating the size of the image based on the text you're putting in it, you'll have to figure out the new size to fit the new text width but I'm sure you can figure that out.

I played around with that multi-line-script "makeImageF".
Added some features, mainly: you can read text-files
or add text as parameter - eg :
imagettftext.php?file=test.txt
imagettftext.php?text=hello|world!

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.

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 fontsif($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.ttfNow one can using constant font name by calling imagettftext:imagettftext($img,12,0,25,28,$color,arialbd,'some text');

Another way of the bellow. After creating a child class of GMIPluggableSet class, which should override two method: getExpression() and getVariables(), throw it to a instance of FontImageGenerator class.For example, the code follows:

If you have problems displaying german umlauts or other chars with an ascii value > 127, try to convert the text-parameter first. The following function converts character-values > 127 (both: UTF-8 + ANSI) to HTML's numeric coded entities:

If you get letters cut off (clipped) by adjacent letters when using imagettftext with transparency (i.e., imagealphablending set to false), try setting imagealphablending back to TRUE before calling the imagettftext function.

I spent days looking for this, couldn't find it, so just made it myself. This is an ultra simple text banner that keeps the text pretty much centered (not perfect when text is angled) vertically and horizontally. Size, font, colors are easy to edit and in HTML version for the colors.

Any additions (maybe for multi-line functionality) can be added if you desire.

<?php### Declare this script will be displayed as a PNG image.header("Content-type: image/png");

I've found that upsampling your text by a factor of 8 or more can really improve the readability of generated text, especially in smaller font sizes (9 or less). I find it also helps with fonts that have kerning to reduce space between letters such as capital T and capital A (TA) where the top-right of the T will be cut off due to GD "features".

I can't tell you, the reader, exactly how to do this, as it will depend on how you are currently generating your text, but essentially what you want to try doing is upsize your font by a factor of 8 and then scale down the resulting image by the same factor.

So if you were using font size 10, use font size 80 and use imagecopyresampled() to divide the width/height down again by 8. The resulting image will be a few pixels different in width / height compared to direct text writing, so make sure to check your image sizes if you are using fixed dimensions.

Play around with other factors, 16 is a bit nicer but results in a higher CPU/RAM load when processing. Any higher is unnecessary I think. If possible you should also cache the image to a file instead of reprocessing it each request.

$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.

for passing hebrew (and maybe other rtl language text) you can use the following code (as suggested by udi and which worked for me) :<?php$returnedtext = iconv("ISO-8859-8", "UTF-8", hebrev(iconv("UTF-8", "ISO-8859-8", $originaltext)));?>