 |
imagettftext (PHP 3, PHP 4, PHP 5) imagettftext -- 用 TrueType 字体向图像写入文本 说明array imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )
- image
图像资源。见 imagecreatetruecolor()。
- size
字体大小。根据 GD 版本不同,应该以像素大小指定(GD1)或点大小(GD2)。
- angle
角度制表示的角度,0 度为从左向右读的文本。更高数值表示逆时针旋转。例如
90 度表示从下向上读的文本。
- x
由 x,y
所表示的坐标定义了第一个字符的基本点(大概是字符的左下角)。这和
imagestring() 不同,其 x,y 定义了第一个字符的左上角。例如
"top left" 为 0, 0。
- y
Y 坐标。它设定了字体基线的位置,不是字符的最底端。
- color
颜色索引。使用负的颜色索引值具有关闭防锯齿的效果。见
imagecolorallocate()。
- fontfile
是想要使用的 TrueType 字体的路径。
根据 PHP 所使用的 GD 库的不同,当 fontfile
没有以 / 开头时则 .ttf
将被加到文件名之后并且会在库定义字体路径中尝试搜索该文件名。
当使用的 GD 库版本低于 2.0.18 时,一个空格字符
而不是分号将被用来作为不同字体文件的“路径分隔符”。不小心使用了此特性将会导致一条警告信息:Warning:
Could not find/open font。对受影响的版本来说唯一解决方案就是将字体移动到不包含空格的路径中去。
很多情况下字体都放在脚本的同一个目录下。下面的小技巧可以减轻包含的问题。
<?php // Set the enviroment variable for GD putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension) $font = 'SomeFont'; ?>
|
- text
文本字符串。
可以包含十进制数字化字符表示(形式为:€)来访问字体中超过位置
127 的字符。UTF-8 编码的字符串可以直接传递。
如果字符串中使用的某个字符不被字体支持,一个空心矩形将替换该字符。
imagettftext() 返回一个含有 8
个单元的数组表示了文本外框的四个角,顺序为坐下角,右下角,右上角,左上角。这些点是相对于文本的而和角度无关,因此“左上角”指的是以水平方向看文字时其左上角。
例子 1. imagettftext() 例子
本例中的脚本将生成一个白色的 400x30 像素 PNG 图像,其中有黑色(带灰色阴影)Arial
字体写的“Testing...”。
<?php // Set the content-type header("Content-type: image/png");
// Create the image $im = imagecreatetruecolor(400, 30);
// Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0);
// The text to draw $text = 'Testing...'; // Replace path by your own font path $font = 'arial.ttf';
// Add some shadow to the text imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg() imagepng($im); imagedestroy($im); ?>
|
|
本函数同时需要 GD 库和
FreeType 库。
参见 imagettfbbox()。
admin at sgssweb dot com
01-May-2006 07: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
30-Apr-2006 02: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
28-Apr-2006 03: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
// Set the content-type
header("Content-type: image/png");
//1line per column
$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;
// Create the image
$im = imagecreatetruecolor ($Image_Width, $Image_Height); /* Create a blank image */
// Create some colors
$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);
// Replace path by your own font path
$font = $_POST['font_name'];
for ($i=0; $i < sizeof($text); $i++) {
//Center the text
$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;
/*
Add the text (***array imagettftext ( resource image, float size, float angle,
int x, int y, int color, string fontfile, string text )***)
*/
imagettftext($im, $Text_Size, 0, $posx, $posy, $black, $font, $text[$i]);
}
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
ugo dot quaisse at gmail dot com
19-Apr-2006 09:03
This is a script that aim at center the (multi) lines :
<?php
header("Content-type: image/png");
//1line per column
$text=array(0=>"line 1",1=>"line 2");
$largeur=500;
$line_height=30;
$hauteur=sizeof($text)*$line_height;
// Create the image
$im = imagecreatetruecolor($largeur, $hauteur);
// Create some colors
$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);
// Replace path by your own font path
$font = 'font.ttf';
for($i=0;$i<=sizeof($text);$i++) {
//Center the text
$size = imagettfbbox(20, 0, $font, $text[$i]);
$long_text = $size[2]+$size[0];
$posx=($largeur-$long_text)/2;
// Add the text
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 06: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
01-Mar-2006 01: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--
29-Jan-2006 04: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
23-Jan-2006 07: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
11-Jan-2006 04: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
24-Oct-2005 03: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
04-Oct-2005 12: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; // flag-bits in $max_mark ( 1111 1000 == 5 times 1)
$max_mark = 248; // marker for a (theoretical ;-)) 5-byte-char and mask for a 4-byte-char;
$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;
// skip non-utf-8-chars
if( $old_val > 127 ) {
$mark = $max_mark;
for($byte_ctr = $max_count; $byte_ctr > 2; $byte_ctr--) {
// actual byte is utf-8-marker?
if( ( $old_val & $mark ) == ( ($mark << 1) & 255 ) ) {
$utf8_marker = $byte_ctr - 1;
break;
}
$mark = ($mark << 1) & 255;
}
}
// marker found: collect following bytes
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--) {
// check if following chars are UTF8 additional data blocks
// UTF8 and ord() > 127
if( (ord($utf{$str_pos + 1}) & 192) == 128 ) {
$new_val = $new_val << 6;
$str_off++;
// no need for Addition, bitwise OR is sufficient
// 63: more UTF8-bytes; 0011 1111
$new_val = $new_val | ( ord( $utf{$str_pos + $str_off} ) & 63 );
}
// no UTF8, but ord() > 127
// nevertheless convert first char to NCE
else {
$new_val = $old_val;
}
}
// build NCE-Code
$html .= '&#'.$new_val.';';
// Skip additional UTF-8-Bytes
$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 03: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
11-Aug-2005 12: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
// Windows 1251 -> Unicode
function win2uni($s)
{
$s = convert_cyr_string($s,'w','i'); // win1251 -> iso8859-5
// iso8859-5 -> unicode:
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 05: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 05: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 08: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 09:14
Hey guys,
check this function if you want to rotate the text around its center and not its "lower left" pivot-point:
<?php
// Put center-rotated ttf-text into image
// Same signature as imagettftext();
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
// retrieve boundingbox
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
// calculate deviation
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0; // deviation left-right
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0; // deviation top-bottom
// new pivotpoint
$px = $x-$dx;
$py = $y-$dy;
return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}
?>
Big up
Phil
Paul Reinheimer
20-Sep-2004 06: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
16-Jul-2004 04: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.
03-Dec-2002 03: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
|  |