當前位置: 首頁> 最新文章列表> PHP imagestring()函數使用教程:在圖像上繪製水平文本

PHP imagestring()函數使用教程:在圖像上繪製水平文本

gitbox 2025-07-18

imagestring()函數簡介

在PHP中, imagestring()是一個用於在圖像上繪製水平文本的內置函數。它廣泛用於生成驗證碼、標註圖像文字等場景,特別適合快速輸出簡單文字內容。

函數的基本語法如下:

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

各參數含義如下:

  • $image :圖像資源,通常由imagecreatetruecolor()imagecreate()創建。
  • $font :系統內置字體,取值範圍為1到5。
  • $x :文字繪製的起始X坐標。
  • $y :文字繪製的起始Y坐標。
  • $string :要繪製的文本字符串。
  • $color :文字顏色,由imagecolorallocate()設置。

創建圖像資源

在使用imagestring()前,需要先創建一個圖像資源。以下代碼創建了一個500×500像素的空白圖像:

 $im = imagecreatetruecolor(500, 500);

設置顏色與字體

接著定義文本顏色、背景顏色與所用字體:

 $font = 4; // 內置字體大小
$color = imagecolorallocate($im, 0, 0, 0); // 黑色文字
$background = imagecolorallocate($im, 255, 255, 255); // 白色背景

繪製文本到圖像

完成圖像與顏色設置後,即可將文字繪製到圖像上。以下示例繪製了“Hello world!”到坐標(50, 50):

 imagestring($im, $font, 50, 50,  "Hello world!", $color);

完整示例:在圖像中央繪製文本

下面是一個完整的使用示例,將文本“Hello World!”繪製在圖像中心,並輸出為PNG格式:

 $im = imagecreatetruecolor(500, 500);
$white = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $white);

$font = 1;
$x = imagesx($im) / 2 - imagefontwidth($font) * strlen("Hello World!") / 2;
$y = imagesy($im) / 2 - imagefontheight($font) / 2;

imagestring($im, $font, $x, $y, "Hello World!", $red);

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

總結

imagestring()是PHP中一個非常實用的圖像處理函數,適用於快速將文本渲染到圖像上。配合顏色設置和坐標定位,可以靈活地生成各種文字圖像輸出,尤其適合驗證碼、動態圖像文字水印等應用。