imagettftext

(PHP 4, PHP 5, PHP 7, PHP 8)

imagettftext用 TrueType 字體向圖像寫入文本

說明

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

使用 TrueType 字體將 指定的 text 寫入圖像。

參數(shù)

image

由圖象創(chuàng)建函數(shù)(例如imagecreatetruecolor())返回的 GdImage 對象。

size

字體的尺寸,單位:點(diǎn)(磅)。

angle

角度制表示的角度,0 度為從左向右讀的文本。更高數(shù)值表示逆時針旋轉(zhuǎn)。例如 90 度表示從下向上讀的文本。

x

x,y 所表示的坐標(biāo)定義了第一個字符的基本點(diǎn)(大概是字符的左下角)。這和 imagestring() 不同,其 x,y 定義了第一個字符的左上角。例如 "top left" 為 0, 0。

y

Y 坐標(biāo)。它設(shè)定了字體基線的位置,不是字符的最底端。

color

顏色索引。使用負(fù)的顏色索引值具有關(guān)閉防鋸齒的效果。見 imagecolorallocate()。

fontfile

是想要使用的 TrueType 字體的路徑。

根據(jù) PHP 所使用的 GD 庫的不同,當(dāng) fontfile 沒有以 / 開頭時則 .ttf 將被加到文件名之后并且會在庫定義字體路徑中嘗試搜索該文件名。

當(dāng)使用的 GD 庫版本低于 2.0.18 時,一個空格字符 而不是分號將被用來作為不同字體文件的“路徑分隔符”。不小心使用了此特性將會導(dǎo)致一條警告信息:Warning: Could not find/open font。對受影響的版本來說唯一解決方案就是將字體移動到不包含空格的路徑中去。

很多情況下字體都放在腳本的同一個目錄下。下面的小技巧可以減輕包含的問題。

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font 'SomeFont';
?>

text

UTF-8 編碼的文本字符串。

可以包含十進(jìn)制數(shù)字化字符表示(形式為:&#8364;)來訪問字體中超過位置 127 的字符。UTF-8 編碼的字符串可以直接傳遞。

命名實(shí)體,比如 &copy; 是不支持的??梢钥紤]使用 html_entity_decode() 來解碼命名實(shí)體為 UTF-8 字符。 (自 PHP 5.0.0 開始 html_entity_decode() 開始支持)

如果字符串中使用的某個字符不被字體支持,一個空心矩形將替換該字符。

返回值

返回一個含有 8 個單元的數(shù)組表示了文本外框的四個角,順序?yàn)樽陆?,右下角,右上角,左上角。這些點(diǎn)是相對于文本的而和角度無關(guān),因此“左上角”指的是以水平方向看文字時其左上角。

更新日志

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

范例

示例 #1 imagettftext() 例子

本例中的腳本將生成一個白色的 400x30 像素 PNG 圖像,其中有黑色(帶灰色陰影)Arial 字體寫的“Testing...”。

<?php
// Set the content-type
header('Content-Type: image/png');

// Create the image
$im imagecreatetruecolor(40030);

// Create some colors
$white imagecolorallocate($im255255255);
$grey imagecolorallocate($im128128128);
$black imagecolorallocate($im000);
imagefilledrectangle($im0039929$white);

// The text to draw
$text 'Testing...';
// Replace path by your own font path
$font 'arial.ttf';

// Add some shadow to the text
imagettftext($im2001121$grey$font$text);

// Add the text
imagettftext($im2001020$black$font$text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

以上例程的輸出類似于:

例子輸出:imagettftext()

注釋

注意:

本函數(shù)同時需要 GD 庫和 ? FreeType 庫。.

參見