imagepstext
(PHP 4, PHP 5)
imagepstext — Рисование текста поверх изображения, используя шрифты PostScript Type1
Описание
$image
, string $text
, resource $font_index
, int $size
, int $foreground
, int $background
, int $x
, int $y
[, int $space
= 0
[, int $tightness
= 0
[, float $angle
= 0.0
[, int $antialias_steps
= 4
]]]] )Рисует текст поверх изображения, используя шрифты PostScript Type1.
Если вы не можете разобраться, как это работает, обратитесь к документации к PostScript.
Список параметров
-
image
-
Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor().
-
text
-
Текст.
-
font_index
-
Ресурс шрифта, возвращаемый функцией imagepsloadfont().
-
size
-
size
задается в пикселах. -
foreground
-
Цвет текста.
-
background
-
Цвет, который будет использоваться при сглаживании шрифта. Пикселы цвета
background
не окрашиваются. Поэтому изображение под текстом не обязано быть однородным. -
x
-
x-координата левого нижнего угла первого символа.
-
y
-
y-координата левого нижнего угла первого символа.
-
space
-
Позволяет изменять размер пробела в шрифте. Значение аргумента добавляется к значению по умолчанию для шрифта и может быть отрицательным. Значение задается в условных единицах, одна единица соответствует 1/1000 ширины буквы m этого шрифта.
-
tightness
-
tightness
позволяет регулировать расстояние между символами. Значение аргумента добавляется к значению по умолчанию для шрифта и может быть отрицательным. Значение задается в условных единицах, одна единица соответствует 1/1000 ширины буквы m этого шрифта. -
angle
-
angle
задается в градусах. -
antialias_steps
-
Позволяет регулировать число цветов, используемых при сглаживании. Возможные значения 4 и 16. Большее значение рекомендуется для размеров шрифтов меньше 20, так как в этом случае неровности лучше видно. Для больших размеров используйте 4, это требует меньше вычислений.
Возвращаемые значения
Функция возвращает массив со следующими элементами:
0 | левая нижняя x-координата |
1 | левая нижняя y-координата |
2 | верхняя правая x-координата |
3 | верхняя правая y-координата |
Примеры
Пример #1 Пример использования imagepstext()
<?php
// Создание изображения
$im = imagecreatetruecolor(200, 200);
// Создание цветов
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// загрузка шрифта PostScript
$font = imagepsloadfont('font.pfm');
// Запись текста
imagepstext($im, 'Простой пример текста', $font, 12, $black, $white, 50, 50);
// Вывод и освобождение памяти
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Примечания
Замечание: Эта функция доступна только в случае, если PHP был скомпилирован с опцией --with-t1lib[=DIR] .
Смотрите также
- imagepsbbox() - Выдает параметры рамки, обрамляющей текст написанный шрифтом PostScript Type1
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Обработка и генерация изображений
- Обработка изображений и GD
- gd_info
- getimagesize
- getimagesizefromstring
- image_type_to_extension
- image_type_to_mime_type
- image2wbmp
- imageaffine
- imageaffinematrixconcat
- imageaffinematrixget
- imagealphablending
- imageantialias
- imagearc
- imagechar
- imagecharup
- imagecolorallocate
- imagecolorallocatealpha
- imagecolorat
- imagecolorclosest
- imagecolorclosestalpha
- imagecolorclosesthwb
- imagecolordeallocate
- imagecolorexact
- imagecolorexactalpha
- imagecolormatch
- imagecolorresolve
- imagecolorresolvealpha
- imagecolorset
- imagecolorsforindex
- imagecolorstotal
- imagecolortransparent
- imageconvolution
- imagecopy
- imagecopymerge
- imagecopymergegray
- imagecopyresampled
- imagecopyresized
- imagecreate
- imagecreatefromgd2
- imagecreatefromgd2part
- imagecreatefromgd
- imagecreatefromgif
- imagecreatefromjpeg
- imagecreatefrompng
- imagecreatefromstring
- imagecreatefromwbmp
- imagecreatefromwebp
- imagecreatefromxbm
- imagecreatefromxpm
- imagecreatetruecolor
- imagecrop
- imagecropauto
- imagedashedline
- imagedestroy
- imageellipse
- imagefill
- imagefilledarc
- imagefilledellipse
- imagefilledpolygon
- imagefilledrectangle
- imagefilltoborder
- imagefilter
- imageflip
- imagefontheight
- imagefontwidth
- imageftbbox
- imagefttext
- imagegammacorrect
- imagegd2
- imagegd
- imagegif
- imagegrabscreen
- imagegrabwindow
- imageinterlace
- imageistruecolor
- imagejpeg
- imagelayereffect
- imageline
- imageloadfont
- imagepalettecopy
- imagepalettetotruecolor
- imagepng
- imagepolygon
- imagepsbbox
- imagepsencodefont
- imagepsextendfont
- imagepsfreefont
- imagepsloadfont
- imagepsslantfont
- imagepstext
- imagerectangle
- imagerotate
- imagesavealpha
- imagescale
- imagesetbrush
- imagesetinterpolation
- imagesetpixel
- imagesetstyle
- imagesetthickness
- imagesettile
- imagestring
- imagestringup
- imagesx
- imagesy
- imagetruecolortopalette
- imagettfbbox
- imagettftext
- imagetypes
- imagewbmp
- imagewebp
- imagexbm
- iptcembed
- iptcparse
- jpeg2wbmp
- png2wbmp
Коментарии
with a font included in t1lib:
<?PHP
Header ("Content-type: image/jpeg");
$im = ImageCreate (350, 45);
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
$font=ImagePsLoadFont("bchbi.pfb");
ImagePsText($im, "Testing... It worked!",
$font, 32, $white, $black, 32, 32);
ImagePsFreeFont($font);
ImageJpeg($im, "", 100);//for best quality... your mileage may vary
ImageDestroy ($im);
?>
Better than using freetype, but with freetype2, the difference is marginal. To flip backround and foreground colors, alternate the order of ImageColorAllocate statements.
If you get outlines (the antialiasing produces these) reverse the $black and $white color identifiers in the ImagePsText function.
Happy PostScripting!
thx,
Neil
One other thing... variables. It is important to convert variables to the proper type before they hit this function. In this respect, ImageTtfText is easier to work with. IE, if you pass a font size from one page to the next, via GPC, it becomes a string type. Sooo... use IntVal() to convert it to an integer type that ImagePsText can digest. In addition you must convert HTML special characters or use chr() to represent special characters. ImagePsFont will not decode to represent a space, use Chr(32) or a space:
<?php
$fontsize=IntVal($fontsize);
$font=ImagePsLoadFont("fonts/IntR.pfb");
ImagePsText($im, $textstring, $font, $fontsize, $textcolor, $background, 0, $fontsize,'','','',16); //note antialias is set
ImagePsFreeFont($font);
?>
thx,
Neil
If you have a programming error in your code, using ImagePsText, sometimes t1lib crashes with an unrecoverable error. Because of this, httpd needs to be restarted.
This problem only occurs if there is a programming error, but can drive you crazy when debugging, if you don't know about it. By killing the parent process(httpd) you "reset" t1lib. When debugging, if you get an error then make a code change, restart httpd before testing it again. This will save hours of frustration. Make it a habit to just restart httpd after every error, and you will be much happier.
Also, to see debugging messages, (if you are rendering x's) comment the jpeg header, and the ImageJpeg statement. You will get beautiful error messages. When you get a blank page, your ImagePsText code is working correctly. Uncomment the Header() and ImageJpeg() and see what you have. You might be passing parameters that render a white image with no text, but the code is working!
Numeric t1lib error messages can be decoded using the t1lib_doc.pdf file that comes with t1lib. PHP simply relays these errors from t1lib to the page. Please don't ask the PHP people about these errors... t1lib has beautiful documentation.... use it: )
thx,
Neil
a note on kernnig:
t1lib tries to load a corresponding afm file in the directory of the font file.
it does this by replacing the extension (.PFB .pfb) with ".afm". note that this has to be a lowercase afm! usually windows-ps-fonts have file names in all-uppercase, so try renaming the *.AFM file to *.afm.
i also noticed that sometimes this gives an error -2. it seems like t1lib chokes on windows-linebreaks in the afm file.
try 'recode dos..lat1 fontfile.afm' and check again.
if it all works, combinations like "Ta" or "Te" should show the second letter slightly moved to the capital T (on normal fonts like Times anyway).
If you use fonts with special chars, remeber to read in the encoded file *.enc with imagepsencodefont ... etc. for Danish, Swedish, German.....
I made a function that makes it easy to align text to the right
of an image. Below you can find the code because for me it
works great. You can also use it to center text as well, if you
like to have that simply remove the -10 and split the result
of $imgwidth and $texwidth
function AlignRight($string, $font, $imgwidth, $fontsize) {
list($lx,$ly,$rx,$ry) = imagepsbbox($string,$font,$fontsize,0,0,0);
$textwidth = $rx - $lx;
$imw = ($imgwidth-10-$textwidth);
return $imw;
}
I found a way to let imagepstext understand 32-bit colors (RGBA) by replacing in gd.c:PHP_FUNCTION(imagepstext)
int _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0;
with
unsigned int _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0;
It is important so make shure that the "text" really is a string.
imagepstext ($im, $text, $font, $textsize, $black, $white, 10, 10);
won't work if $text is undefined, so PHP will quit with an error.
so always write it like this:
imagepstext ($im, "$text", $font, $textsize, $black, $white, 10, 10);
The coordinates given by x, y represent actually a starting point of the text baseline. They represent the lower left corner of the first character only in case that any part of the character doesn't lie below baseline (it works for "Hello" but for "Howdy" it does not - because of letter y). There may be some small differences according to the font and size chosen.
imagepstext() appears to be quite memory intensive and we had a problem where about 50% of the time the script would error. You need to make sure PHP has enough memory assigned to it - we had to increase PHP's allocation from 8MB to 16MB for a simple "hello world" example to work smoothly.
If the png header was commented out it would sometimes error with a message like:
Warning: imagepstext() [function.imagepstext]: T1Lib Error 11 or 14
and if the png header was there it would sometimes say:
The image [...] cannot be displayed, because it contains errors.
The documentation above is bad. It says $font:
"Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont()."
But it can't. When I put in 1,2,3,4,5 I get
"Warning: imagepstext() expects parameter 3 to be resource, integer given"
I get the same thing when using imageloadfont() because imageloadfont() also returns an integer. The documentation should instead say:
"resource returned from imagepsloadfont()."
As of PHP 5.2.13 with bundled GD (2.0.34) antialiasing_steps mustn't be "4 to 16", but "4 or 16". Values from 5 to 15 result in a warning.