Php как увеличить размер шрифта

Как задать шрифт в php

Как изменить размер текста в php?

Возможно оформить размер текста и ссылок, который берется из php?

У меня в основном php файле стоит часть кода.
В нужном месте, на нужных мне страницах я вставляю вторую часть кода — она и выводит текст и ссылки.

В css прописан вид, который мне не подходит и я хочу изменить размер выводимого текста.

Например мне надо

Или, допустим, так Текст и ссылки формирующийся в php

[php-imagemagick] Как изменить размер изображения
Вообщем есть готовый код: convert underlay.png \( 434.jpg \( +clone -threshold -1 -draw «fill.

Изменить размер картинки php
Нахожу только функции, которые берут картинки из директории, у меня же пользователь загружает.

Изменить размер картинки в этом php коде
Здраствуйте, Помогите разобраться где в этом коде меняется размер картинки и как установить.

Как изменить размер картинки
Загружаемый файл оригинал $filename = $_FILES; $uploaddir = ‘../finished goods/boy_62/’;.

Как задать шрифт в php

Помогите пожалуйста, как задать шрифт и размер текста в данном коде?

некорректная постановка вопроса.

В этот код стили вставить можно. Другое дело, что есть делать это неправильно, то «нарушается работа скрипта».

Поскольку мой телепатический приемник на ремонте, тебе придется самому дать здесь пример кода со стилями (только измененные строки), чтобы можно было сказать где именно у тебя ошибка.

Извиняюсь, вопрос поставлен не корректно из-за нехватки знаний в этой области.

Я сделал следующее:

Глючить скрипт перестал, но шрифт в письмах остался прежним.

yan_g
вы размер шрифта прописали для BODY

. посмотрите на письмо.. и где же там тэг body? я не вижу

оформите письмо нормально, как нормальный html документ и будет все хорошо

yan_g
вы размер шрифта прописали для BODY

. посмотрите на письмо.. и где же там тэг body? я не вижу

оформите письмо нормально, как нормальный html документ и будет все хорошо

Опять же, что значит «безрезультатно» ? Ничего не происходит, или все исчезает, или появляется ошибка, какая именно ошибка ? Старайтесь давать немного больше информации, если хотите помощи.

По теме: можно конечно прописать стили так как вы это сделали (правда я не понял почему именно в тэг ), но вообще-то я имел в виду, что вы можете добавить свойство «style» в нужные тэги.

Другой вариант — взять все тело письма в какой-нить контейнер (например

Как сделать обычный шрифт ttf или otf жирным, курсивом или жирным курсивом php

Как сделать обычный шрифт ttf или otf жирным, курсивом или жирным курсивом php?

Понятно, вот дополнение: На картинке вывести текст.

Нужны соответствующие шрифты. Как правило для bold в конце названия шрифта пишется b. Например Arialb.ttf

хм как я понял обычный текст сделать жирным или курсивом в php, то echo « Ваш текст »; так же и с курсивом только вместо b вставляете i P.S. убери пробелы

Всё ещё ищете ответ? Посмотрите другие вопросы с метками php ttf otf или задайте свой вопрос.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.4.14.41981

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

imagettftext

Наносит текст text поверх изображения, используя TrueType шрифт.

До PHP 8.0.0 imagefttext() — это расширенный вариант imagettftext() , который дополнительно поддерживает extrainfo . Начиная с PHP 8.0.0, imagettftext() является псевдонимом imagefttext() .

Список параметров

Объект GdImage , возвращаемый одной из функций создания изображений, например, такой как imagecreatetruecolor() .

Размер шрифта в типографских пунктах.

Угол в градусах, 0 градусов означает расположение текста слева направо. Положительные значения означают поворот текста против часовой стрелки. Например, текст повёрнутый на 90 градусов нужно будет читать снизу вверх.

Координаты x и y определяют отправную точку для первого символа текста (конкретно, левый нижний угол символа). Здесь есть отличие от функции imagestring() , в которой x и y определяют верхний левый угол первого символа. Например, «верхний левый» имеет координаты 0,0.

y-координата. Это позиция базовой линии шрифта, в общем случае она не совпадает с низшей точкой в символе.

Индекс цвета. Использование отрицательных индексов создаёт эффект выключенного сглаживания. Смотрите imagecolorallocate() .

Путь к шрифту TrueType, который вы хотите использовать.

В зависимости от того, какая библиотека GD используется в PHP, если fontfile не начинается с символа / , то к имени файла будет добавлено .ttf и библиотека будет пытаться искать это имя файла по определённому библиотекой пути шрифтов.

При использовании библиотеки GD версии ниже 2.0.18, в качестве разделителя путей для разных файлов шрифтов используется пробел , а не точка с запятой. Непреднамеренное использование этой особенности приведёт к предупреждению: Warning: Could not find/open font . Единственным корректным решением для этих версий библиотек будет перемещение файлов шрифтов в директорию не содержащую пробелов.

Во многих случаях, когда шрифт находится в том же каталоге, что и скрипт PHP, поможет следующий трюк.

Обратите внимание, что open_basedir не применяется к fontfile .

Текстовая строка в кодировке UTF-8.

Для доступа к символам после 127го можно использовать числовые ссылки (в формате: €). Также поддерживается шестнадцатеричный формат (©). Строки в кодировке UTF-8 можно передавать напрямую.

Именованные сущности, вроде ©, не поддерживаются. Используйте функцию html_entity_decode() , чтобы декодировать их в UTF-8 строки.

Если символ не поддерживается шрифтом, вместо него будет нарисован незакрашенный прямоугольник.

Возвращаемые значения

Возвращает массив из 8 элементов, представляющих 4 точки — координаты углов рамки обрамляющей текст. Точки представлены в таком порядке: левый нижний угол, правый нижний, верхний правый, верхний левый. Углы указаны относительно текста, то есть «верхний левый» означает верхний левый угол текста, если расположить его горизонтально. В случае возникновения ошибки функция вернёт false .

Список изменений

Версия Описание
8.0.0 Добавлен параметр options .

Примеры

Пример #1 Пример использования imagettftext()

В этом примере будет создано изображение PNG с белым фоном размером 400×30 пикселов и надписью «Тест. » черным цветом (с серой тенью) шрифтом Arial.

Результатом выполнения данного примера будет что-то подобное:

Примечания

Замечание: Эта функция доступна только в случае, если PHP был скомпилирован с поддержкой freetype (—with-freetype-dir=DIR)

Смотрите также

  • imagettfbbox() — Получение параметров рамки обрамляющей текст написанный TrueType шрифтом
  • imagefttext() — Нанесение текста на изображение, используя шрифты FreeType 2

User Contributed Notes 40 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.

A horizontal centering example:

$tb = imagettfbbox ( 17 , 0 , ‘airlock.ttf’ , ‘Hello world!’ );

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 from the image’s width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

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

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

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

where win2uni is the function that converts win1251 to unicode. here is the code of it
Unicode
function win2uni ( $s )
$s = convert_cyr_string ( $s , ‘w’ , ‘i’ ); // win1251 -> iso8859-5
// iso8859-5 -> unicode:
for ( $result = » , $i = 0 ; $i 175 )? «&#» .( 1040 +( $charcode — 176 )). «;» : $s [ $i ];
>
return $result ;
>
?>

That’s all today! Thanks for your attention!
Alex

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.

$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 1)&&($ln!=$lineno)) $spacing=($slack/($linewordcount[$ln]-1));
else $spacing=$minspacing;
$x=0;
for ($w=0;$w
>
return true;
>

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.

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
else
break;
>
>
else
break;
>
>
$restof = «» ;
for( $l = $m ; $l
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
>

Hi,
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!

If you want to create a paragraph you will need to break your text up into lines and then place each line individually one below the next.

Here’s a basic example of how to do that:

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

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

check this function if you want to rotate the text around its center and not its «lower left» pivot-point:

$font = realpath ( «.» ). «\\arial.ttf» ;

$black = imagecolorallocate ( $im , 0 , 0 , 0 );

$im = imagecreatetruecolor ( 400 , 30 );

imagettftext ( $im , 20 , 0 , 10 , 20 , $black , $font , «coucou» );
?>

Here’s a simple function to wrap text going into an image. It’ll wrap onto as many lines as it needs to, but $angle has to be zero. The $width parameter is the width of the image.

$width ) $ret .=( $ret == «» ? «» : «\n» ). $word ;
> else $ret .=( $ret == «» ? «» : ‘ ‘ ). $word ;
>
>

Just to comment on Sohel Taslims great function.
if anyone needs to add BACKGROUND TRANSPARENCY to this kind of function (which almost does everyone one would want already) then add

$bg_color = imagecolorat($im,1,1);
imagecolortransparent($im, $bg_color);

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

while( $font = $folder -> read ())
if( stristr ( $font , ‘.ttf’ )) //only ttf fonts
$fonts []= $font ;

if (!empty( $fonts ))
echo «

»
. «\n

» ;
sort ( $fonts );
foreach ( $fonts as $font )
echo «

\n» ;
>
else echo «No fonts found from $ffolder » ;
echo «\n » ;
>

else
$im =@ imagecreatetruecolor ( 200 , 30 )
or die( «Cannot Initialize new GD image stream» );

$black = imagecolorallocate ( $im , 0 , 0 , 0 );
$white = imagecolorallocate ( $im , 255 , 255 , 255 );

imagefill ( $im , 0 , 0 , $white );
imagettftext ( $im , 14 , 0 , 5 , 25 , $black , » $ffolder /» . $_GET [ ‘f’ ] , $_GET [ ‘f’ ]);

header ( «Content-type: image/png» );
header ( ‘Content-Length: ‘ . strlen ( $im ));

imagepng ( $im );
imagedestroy ( $im );
>
?>

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

$STRING = «NOTRE PHILOSOPHIE» ;

// —- PRESETS
$FONT = «CantoriaMTStd-SemiBold.otf» ;
$FONT_SIZE = 10.5 ;
$WIDTH = 200 ;
$HEIGHT = 16 ;
$KERNING = 0 ;
$BASELINE = 12 ;
$BG_COLOR = array(
«R» => 5 ,
«G» => 45 ,
«B» => 53
);
$TXT_COLOR = array(
«R» => 188 ,
«G» => 189 ,
«B» => 0
);

// —- CREATE CANVAS + PALETTE
$canvas = imageCreateTrueColor ( $WIDTH * 4 , $HEIGHT * 4 );

$bg_color = imageColorAllocate ( $canvas , $BG_COLOR [ «R» ], $BG_COLOR [ «G» ], $BG_COLOR [ «B» ]);

$txt_color = imageColorAllocate ( $canvas , $TXT_COLOR [ «R» ], $TXT_COLOR [ «G» ], $TXT_COLOR [ «B» ]);

imagefill ( $canvas , 0 , 0 , $bg_color );

$array = str_split ( $STRING );
$hpos = 0 ;

imageCopyResampled ( $final , $canvas , 0 , 0 , 0 , 0 , $WIDTH , $HEIGHT , $WIDTH * 4 , $HEIGHT * 4 );

header ( ‘Content-type: image/png’ );

imageDestroy ( $canvas );
imageDestroy ( $final );

Ref: Craig at frostycoolslug dot com

«Using the negative of a color index has the effect of turning off antialiasing.»

This is true, but only if the image has been created with imagecreate() (as opposed to imagecreatetruecolor())

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

This one caught me out a little bit as confusing, so in an attempt to help others..

«Using the negative of a color index has the effect of turning off antialiasing.»

$textColour = ImageColorAllocate ( $image , 255 , 255 , 255 );
ImageTTFText ( $image , 8 , 0 , 0 , 0 , — $textColour , $font , $text );

Note the — (minus) before the $textColor in ImageTTFText, this creates the negative colour index, and switches off AA on text.

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 \

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.

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:
$strlen && strstr ( $text , ‘ ‘ ) !== FALSE ) $startPoint = strpos ( $text , ‘ ‘ );
$line [ $i ][] = substr ( $text , 0 , $startPoint );
$text = trim ( strstr ( $text , ‘ ‘ ));
>
$line [ $i ][] = trim ( $text );
>
$line [ $i ][] = trim ( $text );
$i ++;
>

return $line ;
>
?>
better solutions is to check input text for lines longer than needed wrap point.

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:
$strlen && stristr ( $text , ‘ ‘ ) !== FALSE ) $startPoint = $strlen — 1 ;
while( substr ( $text , $startPoint , 1 ) != » » ) $startPoint —;
>
$line [ $i ][] = trim ( substr ( $text , 0 , $startPoint ));
$text = substr ( $text , $startPoint );
>
$line [ $i ][] = trim ( $text );
$i ++;
>

return $line ;
>
?>
better solutions is to check input text for lines longer than needed wrap point.

I had some issues trying to get both word wrapping and new line detection but with some of the help from the comments below i got this. (thanks to jwe for the main part of the code here)

$strlen ) $startPoint = $strlen — 1 ;
while( substr ( $text , $startPoint , 1 ) != » » ) $startPoint —;
>
$line [ $i ][] = trim ( substr ( $text , 0 , $startPoint ));
$text = substr ( $text , $startPoint );
>
$line [ $i ][] = trim ( $text );
$i ++;
>

This returns an array for each newline entered and subarray for each wordwrapped line to print.

Array
(
[0] => Array
(
[0] => This is the first long line
[1] => that i entered.
)

[1] => Array
(
[0] => And this is the new line after that.
)
)

Right align out of «webmaster at higher-designs dot com» code

If you want to display a list of fonts in a directory and see what they look like, you could do something like this:

$folder = dir ( «fonts/» ); //The directory where your fonts reside

while( $font = $folder -> read ())

if( stristr ( $font , ‘.ttf’ ))echo ‘ . substr ( $font , 0 , strpos ( $font , ‘.’ )). ‘»>’ ; //only ttf fonts

The file for ‘img.php’ should be something like this:

$font = $_SERVER [ «QUERY_STRING» ];

header ( «Content-type: image/png» );
$im =@ imagecreatetruecolor ( 200 , 30 )or die( «Cannot Initialize new GD image stream» );

$black = imagecolorallocate ( $im , 0 , 0 , 0 );
$white = imagecolorallocate ( $im , 255 , 255 , 255 );

imagefill ( $im , 0 , 0 , $white );

imagettftext ( $im , 18 , 0 , 5 , 25 , $black , «fonts/» . $font , $font );

imagepng ( $im );
imagedestroy ( $im );

I found this line a little confusing:

«May include decimal numeric character references (of the form: €) 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.

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:

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

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

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.

38 ) $startPoint = 37 ;
// find a space to break the line on
while( substr ( $text , $startPoint , 1 ) != » » ) $startPoint —;
>
$line [] = trim ( substr ( $text , 0 , $startPoint ));
$text = substr ( $text , $startPoint );
>
$line [] = trim ( $text );
?>

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.

First of all, thanks sk89q for the func! it was exactly I was looking for.

I made a change. Depending on the letter, the text were incorrect vertical aligned.
I replace the line:
$line_height = $dimensions[1] — $dimensions[7];
for the following:
$line_height = $size+4;

No matter if mama or jeje is written, the vertical position will be the same.

I struggled for moths to do a decent text warp with GD lib. Here is the code that I made use of:

Hope this helps somebody.

Comment to: Sohel Taslim (03-Aug-2007 06:19)

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 🙂

/**
* @name : makeImageF
*
* Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
*
* @param String $text : String to convert into the Image.
* @param String $font : Font name of the text. Kip font file in same folder.
* @param int $Justify : Justify text in image (0-Left, 1-Right, 2-Center).
* @param int $Leading : Space between lines.
* @param int $W : Width of the Image.
* @param int $H : Hight of the Image.
* @param int $X : x-coordinate of the text into the image.
* @param int $Y : y-coordinate of the text into the image.
* @param int $fsize : Font size of text.
* @param array $color : RGB color array for text color.
* @param array $bgcolor : RGB color array for background.
*
*/
function imagettfJustifytext($text, $font=»CENTURY.TTF», $Justify=2, $Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF))

$angle = 0;
$_bx = imageTTFBbox($fsize,0,$font,$text);
$s = split(«[\n]+», $text); // Array of lines
$nL = count($s); // Number of lines
$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W; // If Width not initialized by programmer then it will detect and assign perfect width.
$H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H; // If Height not initialized by programmer then it will detect and assign perfect height.

$im = @imagecreate($W, $H)
or die(«Cannot Initialize new GD image stream»);

$background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]); // RGB color background.
$text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); // RGB color text.

Источник

TypeRus
Adblock
detector
Fonts available in $ffolder
Name Appereance
$font . «?f= $font ‘>