當前位置: 首頁> 最新文章列表> 用imagefontwidth() 和imagestring() 實現動態文本居中

用imagefontwidth() 和imagestring() 實現動態文本居中

M66 2025-05-28

在進行圖像處理時,動態地將文字居中顯示在圖片上,是常見的需求之一。 PHP 的GD 庫提供了一系列函數幫助開發者處理這類任務,其中imagefontwidth()imagestring()是兩個重要的函數。本文將通過一個簡單的示例來說明如何利用這兩個函數實現文本的水平居中顯示。

1. 函數簡介

imagefontwidth()

此函數返回指定字體寬度的像素值。字體編號是GD 預定義的,從1 到5,數字越大,字體越大。

 int imagefontwidth(int $font);

imagestring()

該函數用於將字符串寫入圖像。

 bool imagestring(GdImage $image, int $font, int $x, int $y, string $string, int $color);

參數解釋:

  • $image :圖像資源

  • $font :字體編號(1~5)

  • $x , $y :文本寫入的起始位置

  • $string :要寫入的文本

  • $color :顏色索引值

2. 實現步驟

我們以一個寬度為400 像素,高度為100 像素的圖片為例,將一段文字居中寫入圖片中。

 <?php
// 創建畫布
$width = 400;
$height = 100;
$image = imagecreate($width, $height);

// 設置顏色
$background_color = imagecolorallocate($image, 255, 255, 255); // 白色背景
$text_color = imagecolorallocate($image, 0, 0, 0); // 黑色文字

// 要寫入的文字
$text = "歡迎訪問 m66.net";
$font = 5;

// 計算文本寬度
$text_width = imagefontwidth($font) * strlen($text);

// 計算X坐標,使文本居中
$x = ($width - $text_width) / 2;

// Y坐標(垂直位置)可自定義,這裡簡單設為垂直居中
$y = ($height - imagefontheight($font)) / 2;

// 寫入文字
imagestring($image, $font, $x, $y, $text, $text_color);

// 輸出圖像到瀏覽器
header("Content-Type: image/png");
imagepng($image);

// 釋放內存
imagedestroy($image);
?>

3. 注意事項

  1. 字體限制imagefontwidth()只適用於imagestring()使用的內置字體,如果你需要更精細控製文本樣式和位置,應考慮imagettftext()

  2. 多字節字符strlen()在處理中文時不准確,可使用mb_strlen()替代,或預估字符寬度。

  3. 性能優化:對於頻繁生成的圖像內容,考慮緩存機制避免重複運算。

4. 應用場景

該方法適合用於動態生成驗證碼、圖片水印、二維碼配文、或者諸如https://m66.net這類自定義短網址平台上的圖像文字合成等應用。

通過簡單的幾個函數組合,即可實現實用而靈活的文本居中功能,大大提升用戶體驗和圖像呈現的專業性。