在PHP中, imagestring()是一個用於在圖像上繪製水平文本的內置函數。它廣泛用於生成驗證碼、標註圖像文字等場景,特別適合快速輸出簡單文字內容。
函數的基本語法如下:
bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )
各參數含義如下:
在使用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中一個非常實用的圖像處理函數,適用於快速將文本渲染到圖像上。配合顏色設置和坐標定位,可以靈活地生成各種文字圖像輸出,尤其適合驗證碼、動態圖像文字水印等應用。