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!imagettftext
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
imagettftext
Референца за `function.imagettftext.php` со подобрена типографија и навигација.
imagettftext
(PHP 4, PHP 5, PHP 7, PHP 8)
imagettftext — Напиши текст на сликата користејќи TrueType фонтови
= NULL
GdImage
$image,float
$size,float
$angle,int
$x,int
$y,int
$color,string
$font_filename,string
$text,array
$options = []): array|false
Ги пишува дадените text на сликата користејќи TrueType фонтови.
Забелешка:
за пишување (оставјајќи го стрингот недопрен). imagefttext() беше проширена варијанта на imagettftext() што дополнително го поддржуваше
extrainfoКако на PHP 8.0.0, imagettftext() е псевдоним за imagefttext().
Параметри
-
image А GdImage не применува никакво полнење, така што ширината на сликата мора да биде множител на 8. Ова ограничување веќе не важи од PHP 7.0.9. imagecreatetruecolor().
size-
Големината на фонтот во точки.
angle-
Аголот во степени, при што 0 степени е читање текст од лево кон десно. Поголемите вредности претставуваат ротација спротивно од стрелките на часовникот. На пример, вредност од 90 би резултирала со читање текст од дното кон врвот.
x-
Координатите дадени од
xandyќе ја дефинираат основната точка на првиот знак (приближно долниот лев агол на знакот). Ова е различно од imagestring(), каде штоxandyги дефинира горниот лев агол на првиот знак. На пример, „горе лево“ е 0, 0. y-
Y-ордината. Ова ја поставува позицијата на основната линија на фонтот, а не најдолниот дел од знакот.
color-
Индексот на боја. Користењето на негативен индекс на боја има ефект на исклучување на анти-алиасингот. Види imagecolorallocate().
fontfile-
Патеката до TrueType фонтот што сакате да го користите.
Во зависност од тоа која верзија на GD библиотеката ја користи PHP, when
fontfileне започнува со водечки/then.ttfќе биде додадено на името на датотеката и библиотеката ќе се обиде да го пребара тоа име на датотека по патека за фонтови дефинирана од библиотеката.Кога се користат верзии на GD библиотеката пониски од 2.0.18, а
spaceкарактер, наместо точка-запевка, беше користен како 'разделувач на патеки' за различни фонтски датотеки. Ненамерната употреба на оваа функција ќе резултира со порака за предупредување:Warning: Could not find/open fontкарактер, наместо точка и запирка, беше користен како 'разделувач на патеката' за различни фонтски датотеки. Ненамерната употреба на оваа функција ќе резултира со предупредувачка порака:. За овие засегнати верзии, единственото решение е да се премести фонтот во патека што не содржи празни места.
<?php
// Set the environment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>Забелешка:
Имајте предвид дека open_basedir does not Во многу случаи каде што фонтот се наоѓа во истата директориум со скриптата што го користи, следниот трик ќе ги ублажи сите проблеми со вклучување.
fontfile. text-
се однесува на
Текстуалниот стринг во UTF-8 кодирање.
€Може да вклучува децимални нумерички референци на карактери (во форма:©) за пристап до карактери во фонт надвор од позиција 127. Хексадецималниот формат (како) е поддржан. Стрингови во UTF-8 кодирање може да се поминат директно.
©Именувани ентитети, како html_entity_decode() ,не се поддржани. Размислете за користење
options-
за декодирање на овие именувани ентитети во UTF-8 стрингови.
linespacingАко се користи карактер во стринг што не е поддржан од фонтот, шуплив правоаголник ќе го замени карактерот. float value.
Вратени вредности
Низа со false при грешка.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
На options е додадена.
|
Примери
Пример #1 imagettftext() example
клуч што држи
<?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);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// 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);
?>Горниот пример ќе прикаже нешто слично на:
Белешки
Забелешка: Враќа низа со 8 елементи што претставуваат четири точки што ја прават границата на текстот. Редоследот на точките е долна лева, долна десна, горна десна, горна лева. Точките се релативни на текстот без оглед на аголот, така што "горна лева" значи во горниот лев агол кога текстот го гледате хоризонтално. ВраќаОвој примерок скрипта ќе произведе бела PNG 400x30 пиксели, со зборовите "Testing..." во црно (со сива сенка), во фонтот Arial.)
Види Исто така
- imagettfbbox() Оваа функција е достапна само ако PHP е компајлиран со поддршка за freetype (
- imagefttext() --with-freetype-dir=DIR
- imagestring() - Нацртај стринг хоризонтално
Белешки од корисници Управување со PDO конекции
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.)
eg.
$image = ImageCreateFromJPEG( "sample.jpg" );
$cor = imagecolorallocate($image, 0, 0, 0);
$font = 'arial.ttf';
$a = imagettftextjustified($image, 20, 0, 50, 50, $color, $font, "Shree", 500, $minspacing=3,$linespacing=1);
header('Content-type: image/jpeg');
imagejpeg($image,NULL,100);
function imagettftextjustified(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width, $minspacing=3,$linespacing=1)
{
$wordwidth = array();
$linewidth = array();
$linewordcount = array();
$largest_line_height = 0;
$lineno=0;
$words=explode(" ",$text);
$wln=0;
$linewidth[$lineno]=0;
$linewordcount[$lineno]=0;
foreach ($words as $word)
{
$dimensions = imagettfbbox($size, $angle, $font, $word);
$line_width = $dimensions[2] - $dimensions[0];
$line_height = $dimensions[1] - $dimensions[7];
if ($line_height>$largest_line_height) $largest_line_height=$line_height;
if (($linewidth[$lineno]+$line_width+$minspacing)>$max_width)
{
$lineno++;
$linewidth[$lineno]=0;
$linewordcount[$lineno]=0;
$wln=0;
}
$linewidth[$lineno]+=$line_width+$minspacing;
$wordwidth[$lineno][$wln]=$line_width;
$wordtext[$lineno][$wln]=$word;
$linewordcount[$lineno]++;
$wln++;
}
for ($ln=0;$ln<=$lineno;$ln++)
{
$slack=$max_width-$linewidth[$ln];
if (($linewordcount[$ln]>1)&&($ln!=$lineno)) $spacing=($slack/($linewordcount[$ln]-1));
else $spacing=$minspacing;
$x=0;
for ($w=0;$w<$linewordcount[$ln];$w++)
{
imagettftext($image, $size, $angle, $left + intval($x), $top + $largest_line_height + ($largest_line_height * $ln * $linespacing), $color, $font, $wordtext[$ln][$w]);
$x+=$wordwidth[$ln][$w]+$spacing+$minspacing;
}
}
return true;
}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!
AlexIf 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!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_pos + $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_pos + $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
}
}
?>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
PhilHi,
for the dummies (like myself) if you are having problems including your font file, prefix the file name with ./
On my development server the following worked fine
$myfont = "coolfont.ttf";
on my hosting server the only way i could get the font to work was as follows
$myfont = "./coolfont.ttf";
hope this helps someone out!