PHP Conference Japan 2024

imageloadfont

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

imageloadfont載入新字型

說明

imageloadfont(字串 $filename): GdFont|false

imageloadfont() 載入使用者自訂的點陣圖並返回其識別碼。

參數

檔案名稱

字體檔案格式目前是二進位制且與架構相關。這表示您應該在與執行 PHP 的機器相同類型的 CPU 上產生字體檔案。

字體檔案格式
位元組位置 C 資料類型 說明
位元組 0-3 int 字體中的字元數
位元組 4-7 int 字體中第一個字元的數值(通常是 32,代表空格)
位元組 8-11 int 每個字元的像素寬度
位元組 12-15 int 每個字元的像素高度
位元組 16- char 包含字元資料的陣列,每個字元中每個像素佔用一個位元組,總共 (字元數 * 寬度 * 高度) 個位元組。

傳回值

傳回一個 GdFont 實例,如果失敗則傳回 false

更新日誌

版本 說明
8.1.0 現在傳回一個 GdFont 實例;先前傳回的是 int

範例

範例 #1 imageloadfont() 使用範例

<?php
// 建立新的影像實例
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// 將背景設為白色
imagefilledrectangle($im, 0, 0, 49, 19, $white);

// 載入 gd 字體並寫入 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);

// 輸出到瀏覽器
header('Content-type: image/png');

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

參見

新增註記

使用者貢獻的註記 3 則註記

siker at norwinter dot com
19 年前
假設字型檔案中唯一「與架構相關」的部分是位元組順序,我寫了一個簡單的 Python 腳本來進行兩者之間的轉換。它只在一台機器上的單一字型上進行過測試,所以不要完全依賴它。它所做的只是交換前四個整數的位元組順序。

#!/usr/bin/env python

f = open("myfont.gdf", "rb");
d = open("myconvertedfont.gdf", "wb");

for i in xrange(4)
b = [f.read(1) for j in xrange(4)];
b.reverse();
d.write(''.join(b));

d.write(f.read());

我成功地使用這個腳本將下方其中一個字型連結中的 anonymous.gdf 轉換成可在 Mac OS X 上使用的格式。
alex at bestgames dot ro
19 年前
用於防止網站自動註冊的驗證碼產生。

函式參數如下:
$code - 您要隨機產生的驗證碼
$location - 要產生的圖片的相對位置
$fonts_dir - GDF 字型目錄的相對位置

此函式將建立一個包含您提供的驗證碼的圖片,並將其儲存在指定的目錄中,檔案名稱由驗證碼的 MD5 雜湊值組成。

您可以在字型目錄中插入任意數量的字型類型,並使用隨機名稱。

<?php
function generate_image($code, $location, $fonts_dir)
{
$image = imagecreate(150, 60);
imagecolorallocate($image, rand(0, 100), rand(100, 150), rand(150, 250));
$fonts = scandir($fonts_dir);

$max = count($fonts) - 2;

$width = 10;
for (
$i = 0; $i <= strlen($code); $i++)
{
$textcolor = imagecolorallocate($image, 255, 255, 255);
$rand = rand(2, $max);
$font = imageloadfont($fonts_dir."/".$fonts[$rand]);

$fh = imagefontheight($font);
$fw = imagefontwidth($font);

imagechar($image, $font, $width, rand(10, 50 - $fh), $code[$i], $textcolor);
$width = $width + $fw;

}

imagejpeg($image, $location."/".md5($code).".jpg", 100);
imagedestroy($image);

return
$code;

}

?>
matthew at exanimo dot com
19 年前
提醒:GD 字型沒有反鋸齒。如果您打算使用現有的 (TrueType) 字型,建議您考慮使用 imagettftext() 取代 phillip 的函式。
To Top