当前位置: 首页> 函数类别大全> imagettftext

imagettftext

使用TrueType字体将文本写入图像
名称:imagettftext
分类:图像处理GD
所属语言:php
一句话介绍:使用TrueType字体将文本写入图像

imagettftext 函数

适用PHP版本:PHP 4及以上版本

函数说明

imagettftext() 函数用于将文本绘制到图像上,支持TrueType字体(TTF)的渲染。

函数语法

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

参数

  • $image (resource) — 目标图像资源。
  • $size (float) — 字体大小。
  • $angle (float) — 字体角度,正值为逆时针旋转。
  • $x (int) — 文本的起始X坐标。
  • $y (int) — 文本的起始Y坐标。
  • $color (int) — 文本颜色,通常是通过调用imagecolorallocate()获得的颜色值。
  • $fontfile (string) — 字体文件路径,必须是TrueType字体文件(.ttf)。
  • $text (string) — 要绘制的文本内容。

返回值

成功时返回true,失败时返回false。

示例

以下示例将使用TrueType字体将文本绘制到图像上:

示例代码

  <?php
  // 创建一个空白图像
  $image = imagecreatetruecolor(400, 200);
<p>// 设置背景颜色<br>
$bg_color = imagecolorallocate($image, 255, 255, 255);<br>
imagefill($image, 0, 0, $bg_color);</p>
<p>// 设置文本颜色(黑色)<br>
$text_color = imagecolorallocate($image, 0, 0, 0);</p>
<p>// 字体文件路径<br>
$font_path = 'path/to/font.ttf';</p>
<p>// 使用imagettftext绘制文本<br>
imagettftext($image, 20, 0, 50, 100, $text_color, $font_path, 'Hello, World!');</p>
<p>// 输出图像到浏览器<br>
header('Content-Type: image/png');<br>
imagepng($image);</p>
<p>// 销毁图像资源<br>
imagedestroy($image);<br>
?><br>

示例代码的说明

  • 首先,使用 imagecreatetruecolor() 创建一个 400x200 像素的空白图像。
  • 使用 imagecolorallocate() 设置背景颜色为白色。
  • 使用 imagecolorallocate() 设置文本颜色为黑色。
  • 提供一个 TrueType 字体的路径和要显示的文本("Hello, World!")。
  • 使用 imagettftext() 将文本绘制到图像上。
  • 最后,使用 imagepng() 输出图像,使用 header() 设置响应类型,并用 imagedestroy() 销毁图像资源。
同类函数