|
 |
imagettftext (PHP 3, PHP 4, PHP 5) imagettftext -- Write text to the image using TrueType fonts Descriptionarray imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )
- image
The image resource. See 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
putenv('GDFONTPATH=' . realpath('.'));
$font = 'SomeFont';
?>
|
- text
The text string.
May include decimal numeric character references (of the form:
€) to access characters in a font beyond position 127.
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.
imagettftext() 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.
Пример 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
header("Content-type: image/png");
$im = imagecreatetruecolor(400, 30);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
$text = 'Testing...';
$font = 'arial.ttf';
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
imagepng($im);
imagedestroy($im);
?>
|
|
This function requires both the GD library and the FreeType library.
See also imagettfbbox().
imagettftext
admin at sgssweb dot com
01-May-2006 04:08
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:
<?php
require_once 'package.fig.php';
class SampleFontImagePluggableSet
extends GMIPluggableSet
{
var $defaultVariables = array(
"text" => null,
"size" => null,
"font" => null,
"color" => "0x000000",
"alpha" => "100",
"padding" => 0,
"width" => null,
"height" => null,
"align" => "left",
"valign" => "middle",
"bgcolor" => "0xffffff",
"antialias" => 4
);
function SampleFontImagePluggableSet() {
parent::GMIPluggableSet();
}
function getExpression() {
return "size {width}, {height};".
"autoresize none;".
"type gif, 256, {color: {bgcolor}};".
"padding {padding};".
"color {color: {bgcolor}};".
"fill;".
"color {color: {color}, {alpha}};".
"antialias {antialias};".
"font {font}, {size};".
"string {text}, 0, 0, {width}, {height}, {align}, {valign};";
}
function getVariables() {
return array_merge($this->defaultVariables, $_GET);
}
}
$pluggableSet = new SampleFontImagePluggableSet();
$fig = new FontImageGenerator();
$fig->setPluggableSet($pluggableSet);
$fig->execute();
?>
This output a image with the text defined in $_GET['text'], the font in $_GET['font'], the text color in $_GET['color'], the background in $_GET['bgcolor'], and so on.
The script file is available at: http://sgssweb.com/experiments/?file=PHPFontImageGenerator .
admin at sgssweb dot com
29-Apr-2006 11:17
I wrote two classes: PHP Abstract Drawing Toolkit and PHP Graphics, the elements of PHP Font Image Generator2. An instance of the class Graphics can draw multi-sampling antialiased text, 7 horizontal alignment of text box (left, center, right, left-adjust, center-adjust, right-adjust, adjust), 3 vertical alignment (top, middle, bottom), and other Java-like methods.
<?php
require_once "package.graphics.php";
$canvas = new Canvas();
$canvas->setSize(400, 400);
$g =& $canvas->getGraphics();
$g->setColor(new Color(0xffffff));
$g->fill();
$g->setColor(new Color(0, 0, 0, 80));
$g->setFont(new Font($_POST['font'], 20));
$g->drawString($_POST['text'], 0, 0, 400, 400, 'center-adjust', 'middle');
$canvas->complete();
$canvas->output();
?>
The class script is here.
http://sgssweb.com/experiments/?file=PHPFontImageGenerator2
jpetsel at riverviewtech dot net
27-Apr-2006 12:06
I was looking at ugo's center and it was great for left to right centering, but it wouldn't center up and down. So with some changes to suit my needs this is what I came up with. Some of the notations are just for my edifcation so may mean nothing for you all but you will see I added a $posy that helps with centering up and down. I was also feeding my feilds from a form.
<?php
header("Content-type: image/png");
$text=array(0=>$_POST['linei'],1=>$_POST['lineii'],
2=>$_POST['lineiii'],3=>$_POST['lineiv'],4=>$_POST['linev']);
$Image_Width=400;
$Text_Size=$_POST['textsize'];
$Image_Height=400;
$im = imagecreatetruecolor ($Image_Width, $Image_Height); $white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 1, 1, 398, 398, $white);
$font = $_POST['font_name'];
for ($i=0; $i < sizeof($text); $i++) {
$Text_Box_Size = imagettfbbox($Text_Size, 0, $font, $text[$i]);
$Text_Box_Width = abs($Text_Box_Size[2] + $Text_Box_Size[0]);
$Text_Box_Height = abs($Text_Box_Size[7] + $Text_Box_Size[1]);
$Text_Height = $Text_Height + $Text_Box_Height;
$posx = ($Image_Width - $Text_Box_Width) / 2;
$posy = ($Image_Height - $Text_Box_Height * sizeof($text)) / 2 + $Text_Height;
imagettftext($im, $Text_Size, 0, $posx, $posy, $black, $font, $text[$i]);
}
imagepng($im);
imagedestroy($im);
?>
ugo dot quaisse at gmail dot com
19-Apr-2006 06:03
This is a script that aim at center the (multi) lines :
<?php
header("Content-type: image/png");
$text=array(0=>"line 1",1=>"line 2");
$largeur=500;
$line_height=30;
$hauteur=sizeof($text)*$line_height;
$im = imagecreatetruecolor($largeur, $hauteur);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 225, 225, 225);
$blue = imagecolorallocate($im, 0, 62, 126);
imagefilledrectangle($im, 0, 0, $largeur, $hauteur, $white);
$font = 'font.ttf';
for($i=0;$i<=sizeof($text);$i++) {
$size = imagettfbbox(20, 0, $font, $text[$i]);
$long_text = $size[2]+$size[0];
$posx=($largeur-$long_text)/2;
imagettftext($im, 20, 0, $posx, $line_height+$line_height*$i, $blue, $font, $text[$i]);
}
imagepng($im);
imagedestroy($im);
?>
mats dot engstrom at gmail dot com
28-Mar-2006 02:23
I'll second the note from --colobri--.
Just adding --with-ttf and --with-freetype-dir=/usr/lib/ on the ./configure and then doing a "make; make install" is not enough.
I had to do a "make clean" and then a "make install" in order to get the FreeType-support enabled.
Here are my relevant ./configure lines:
--with-gd \
--enable-gd-native-ttf \
--with-ttf \
--with-freetype-dir=/usr/lib/ \
--with-jpeg-dir=/usr/lib/libjpeg.so.62 \
--enable-exif \
admin at phpru dot com
28-Feb-2006 09:52
On my conf: php5.1.2+apache 1.33
iconv() function works very well with all cyrillic encodings, so you needn't to write your function like win2uni
--Colibri--
28-Jan-2006 12:53
If you have configured and compiled PHP with all the necessary command-line options and still get the error:
Fatal error: Call to undefined function imagettftext()
Try doing a "make clean" before building the php apache module:
./configure [...]
make clean
make
make install
This may solve your problem (and hopefully keep you from wasting hours trying different compile options!)
nospam at nospam dot nospam
22-Jan-2006 03:51
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.
Mer`Zikain
10-Jan-2006 12:41
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.
for($i=0;$i<strlen($text);$i++){
// Get single character
$value=substr($text,$i,1);
if($pval){ // check for existing previous character
list($lx,$ly,$rx,$ry) = imagettfbbox($fontsize,0,$font,$pval);
$nxpos+=$rx+3;
}else{
$nxpos=0;
}
// Add the letter to the image
imagettftext($im, $fontsize, 0, $nxpos, $ypos, $fontcolor, $font, $value);
$pval=$value; // save current character for next loop
}
a4W
23-Oct-2005 12:28
This function will make your text bold:
<?php
function drawboldtext($image, $size, $angle, $x_cord, $y_cord, $r, $g, $b, $fontfile, $text)
{
$color = ImageColorAllocate($image, $r, $g, $b);
$_x = array(1, 0, 1, 0, -1, -1, 1, 0, -1);
$_y = array(0, -1, -1, 0, 0, -1, 1, 1, 1);
for($n=0;$n<=8;$n++)
{
ImageTTFText($image, $size, $angle, $x_cord+$_x[$n], $y_cord+$_y[$n], $color, $fontfile, $text);
}
}
?>
limalopex.eisfux.de
03-Oct-2005 09:17
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:
<?php
define('EMPTY_STRING', '');
function foxy_utf8_to_nce(
$utf = EMPTY_STRING
) {
if($utf == EMPTY_STRING) return($utf);
$max_count = 5; $max_mark = 248; $html = EMPTY_STRING;
for($str_pos = 0; $str_pos < strlen($utf); $str_pos++) {
$old_chr = $utf{$str_pos};
$old_val = ord( $utf{$str_pos} );
$new_val = 0;
$utf8_marker = 0;
if( $old_val > 127 ) {
$mark = $max_mark;
for($byte_ctr = $max_count; $byte_ctr > 2; $byte_ctr--) {
if( ( $old_val & $mark ) == ( ($mark << 1) & 255 ) ) {
$utf8_marker = $byte_ctr - 1;
break;
}
$mark = ($mark << 1) & 255;
}
}
if($utf8_marker > 1 and isset( $utf{$str_pos + 1} ) ) {
$str_off = 0;
$new_val = $old_val & (127 >> $utf8_marker);
for($byte_ctr = $utf8_marker; $byte_ctr > 1; $byte_ctr--) {
if( (ord($utf{$str_pos + 1}) & 192) == 128 ) {
$new_val = $new_val << 6;
$str_off++;
$new_val = $new_val | ( ord( $utf{$str_pos + $str_off} ) & 63 );
}
else {
$new_val = $old_val;
}
}
$html .= '&#'.$new_val.';';
$str_pos = $str_pos + $str_off;
}
else {
$html .= chr($old_val);
$new_val = $old_val;
}
}
return($html);
}
?>
alexey at NOSPAMPLS dot ozerov dot de
31-Aug-2005 12:30
Notice that the path to the TrueType font has to be included in open_basedir list if open_basedir restriction is activated in php.ini.
gav-alex at bk dot ru
10-Aug-2005 09:05
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
<?php
imagettftext($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 imagettftext
you simply have to change the function argument like this
<?php
imagettftext($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
function win2uni($s)
{
$s = convert_cyr_string($s,'w','i'); for ($result='', $i=0; $i<strlen($s); $i++) {
$charcode = ord($s[$i]);
$result .= ($charcode>175)?"&#".(1040+($charcode-176)).";":$s[$i];
}
return $result;
}
?>
That's all today! Thanks for your attention!
Alex
BuddyHacker
21-Jul-2005 02:55
A correction to Paul Reinheimer's note above regarding this PHP error:
Fatal error: Call to undefined function imagettftext().
Paul states that you need XPM libraries to resolve this issue. This is not true. There is an error message that originates from "configure" which mistakenly shows itself when other components are missing. For instance, if you tell "configure" to add JPEG support, and it can't find the libraries, it will tell you it can't find the JPEG libraries AND it will recommend adding --with-xpm to solve the problem. This recommendation is ill-placed and misleading.
I received the same error message above, along with the recommendation to add XPM supprt. However I resolved it by adding the --with-freetype-dir AND --enable-gd-native-ttf options to the "configure" command line. I did _not_ need XPM.
There are other variations to this error message, such as the script recommending adding JPEG support or PNG support to resolve it's own inability to locate other libraries. The script needs some cleanup in order to fix these poorly placed recommendations.
FYI, imagettftext() is a call to one of the truetype fonts functions. It is NOT related in any way to the XPM libraries, so it is not required unless you explicitly want XPM functionality.
nick
01-Apr-2005 01:18
A trivial function to get right or centre aligned horizontal text:
function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L') {
//check width of the text
$bbox = imagettfbbox ($size, $angle, $font, $text);
$textWidth = $bbox[2] - $bbox[0];
switch ($alignment) {
case "R":
$x -= $textWidth;
break;
case "C":
$x -= $textWidth / 2;
break;
}
//write text
imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);
}
erik[at]phpcastle.com
04-Mar-2005 04:46
Remember!!!
When uploading a font to your website you have to set the transfer mode to binary. It took me some time to find out :P. Tried to download the font from my website and it was spoiled.
In your script, the path to your font, use realpath("arial.ttf") so there is no confusion about that.
pillepop2003 at nospam dot yahoo dot de
12-Jan-2005 05:14
Hey guys,
check this function if you want to rotate the text around its center and not its "lower left" pivot-point:
<?php
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0; $dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0; $px = $x-$dx;
$py = $y-$dy;
return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}
?>
Big up
Phil
Paul Reinheimer
20-Sep-2004 03:33
If you compiled PHP yourself but get an error:
Fatal error: Call to undefined function imagettftext().
You need to compile PHP with more options.
--with-gd
--enable-gd-native-ttf
--with-png
--with-zlib-dir=/usr/local/lib/zlib-1.2.1
--with-ttf
--with-jpeg-dir=/usr/local/lib/jpeg-6b/
--with-freetype-dir=/usr/local/lib/freetype-2.1.9/
--with-xpm-dir=/usr/X11R6/
The next set deal with setting up GD, and the appropriate options. Just enabling GD, ttf, png & jpeg is NOT enough. You also need Freetype and XPM.
plusplus7 at hotmail dot com
15-Jul-2004 01:37
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.
02-Dec-2002 11:13
If you have an older version of the GD library, but wish to use a font file which has spaces in the path, you should convert the path into DOS style names. This will only work on windows.
For example:
C:\reallylongpath\reallylongpath\font.ttf
Would become:
C:\really~1\really~1\font.ttf
| |