百科狗-知识改变命运!
--

imagettftext() - gd函数(图像处理)

乐乐1年前 (2023-11-21)阅读数 19#技术干货
文章标签字体

imagettftext()

(PHP 4, PHP 5, PHP 7)

用 TrueType 字体向图像写入文本

说明

imagettftext(resource $image,float $size,float $angle,int $x,int $y,int $color,string $fontfile,string $text): array

使用 TrueType 字体将指定的$text写入图像。

参数

$image

由图象创建函数(例如imagecreatetruecolor())返回的图象资源。

$size

字体的尺寸。根据 GD 的版本,为像素尺寸(GD1)或点(磅)尺寸(GD2)。

$angle

角度制表示的角度,0 度为从左向右读的文本。更高数值表示逆时针旋转。例如 90 度表示从下向上读的文本。

$x

由$x,$y所表示的坐标定义了第一个字符的基本点(大概是字符的左下角)。这和imagestring()不同,其$x,$y定义了第一个字符的左上角。例如"top left"为 0, 0。

$y

Y 坐标。它设定了字体基线的位置,不是字符的最底端。

$color

imagettftext() - gd函数(图像处理)

颜色索引。使用负的颜色索引值具有关闭防锯齿的效果。见imagecolorallocate()。

$fontfile

是想要使用的 TrueType 字体的路径。

根据 PHP 所使用的 GD 库的不同,当$fontfile没有以/开头时则.ttf将被加到文件名之后并且会在库定义字体路径中尝试搜索该文件名。

当使用的 GD 库版本低于 2.0.18 时,一个空格字符而不是分号将被用来作为不同字体文件的“路径分隔符”。不小心使用了此特性将会导致一条警告信息:Warning: Could not find/open font。对受影响的版本来说唯一解决方案就是将字体移动到不包含空格的路径中去。

很多情况下字体都放在脚本的同一个目录下。下面的小技巧可以减轻包含的问题。

$text

UTF-8 编码的文本字符串。

可以包含十进制数字化字符表示(形式为:€)来访问字体中超过位置 127 的字符。UTF-8 编码的字符串可以直接传递。

命名实体,比如©是不支持的。可以考虑使用html_entity_decode()来解码命名实体为 UTF-8 字符。(自 PHP 5.0.0 开始 html_entity_decode()开始支持)

如果字符串中使用的某个字符不被字体支持,一个空心矩形将替换该字符。

返回值

返回一个含有 8 个单元的数组表示了文本外框的四个角,顺序为坐下角,右下角,右上角,左上角。这些点是相对于文本的而和角度无关,因此“左上角”指的是以水平方向看文字时其左上角。

更新日志

版本说明
5.2.0 It is now possible to specify an hexadecimal entity in$text.

范例

imagettftext()例子

本例中的脚本将生成一个白色的 400x30 像素 PNG 图像,其中有黑色(带灰色阴影)Arial 字体写的“Testing...”。

以上例程的输出类似于:

注释

Note:

本函数同时需要 GD 库和» FreeType库。.

参见

  • imagettfbbox()取得使用 TrueType 字体的文本的范围
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 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:

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
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;$ln1)&&($ln!=$lineno)) $spacing=($slack/($linewordcount[$ln]-1));
else $spacing=$minspacing;
$x=0;
for ($w=0;$w
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: 
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);
ABOVE the "if($L_R_C == 0){ //Justify Left" line
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

That's all today! Thanks for your attention!
Alex
Just in case you were--like me--unaware of this, in Windows, ttf fonts don't necessarily antialias at all font sizes. Arial appears to work at all sizes but Calibri, for example, only antialiases at a point size of 8 and then at all sizes 16 and up. Not only that but at fonts sizes like 10 and 12 characters don't print at the expected angle: the characters are all printed upright on an angled baseline.
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);
to 
$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.
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!
Hey guys,
check this function if you want to rotate the text around its center and not its "lower left" pivot-point:

Big up
Phil
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. 
Another way to wrap and center using wordwrap and learning the number of lines in the result of that wordwrap 
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.
For anyone attempting to print black barcodes, and trying to turn of anti-aliasing, remember that -1 * [0,0,0] is 0, not -0.
If 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!
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.
    
    if ($Justify == 0){ //Justify Left
      imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
    } else {
      // Create alpha-nummeric string with all international characters - both upper- and lowercase
      $alpha = range("a", "z");
      $alpha = $alpha.strtoupper($alpha).range(0, 9);
      // Use the string to determine the height of a line
      $_b = imageTTFBbox($fsize,0,$font,$alpha);
      $_H = abs($_b[5]-$_b[3]);
      $__H=0;
      for ($i=0; $i

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)