在 GD 圖像處理中,繪製文字前需知道其佔用寬高,以便置中、換行或排版。PHP 提供 imagettfbbox() 回傳文字外框 8 個座標點,透過簡單運算即可獲得寬度與高度。
<?php
define('F_SIZE', 8); // 字體大小 (pt)
define('F_FONT', 'arial.ttf'); // 字體檔路徑 (需可讀)
/** 取得文字外框座標陣列 */
function get_bbox($text) {
return imagettfbbox(F_SIZE, 0, F_FONT, $text);
}
/** 計算文字高度 */
function text_height($text) {
$box = get_bbox($text);
// $box[3] 右下角 Y, $box[5] 右上角 Y
return $box[3] - $box[5];
}
/** 計算文字寬度 */
function text_width($text) {
$box = get_bbox($text);
// $box[4] 右下角 X, $box[6] 左下角 X
return $box[4] - $box[6];
}
// 使用範例
$str = "Hello World";
echo "Width: " . text_width($str) . "px
| 索引 | 位置 |
|---|---|
| 0 | 左下角 X |
| 1 | 左下角 Y |
| 2 | 右下角 X |
| 3 | 右下角 Y |
| 4 | 右上角 X |
| 5 | 右上角 Y |
| 6 | 左上角 X |
| 7 | 左上角 Y |
\n),imagettfbbox 僅計算單行,需自行分行處理。