引言
準(zhǔn)備工作
在開始之前,請(qǐng)確保已安裝以下軟件和庫:
- PHP環(huán)境:安裝PHP解釋器和相關(guān)擴(kuò)展。
- GD庫:PHP的GD庫支持圖像處理功能,需要安裝并啟用。
- 圖像編輯軟件:如Photoshop、GIMP等,用于編輯和預(yù)覽效果。
PHP添加文字到圖片
- 加載圖片:使用
imagecreatefromjpeg()
、imagecreatefrompng()
等函數(shù)加載圖片。 - 創(chuàng)建文字:使用
imagestring()
、imagettftext()
等函數(shù)創(chuàng)建文字。 - 設(shè)置文字樣式:通過設(shè)置字體大小、顏色、角度等參數(shù)調(diào)整文字樣式。
- 輸出圖片:使用
imagejpeg()
、imagepng()
等函數(shù)輸出圖片。
示例代碼
<?php
// 加載圖片
$image = imagecreatefromjpeg('example.jpg');
// 創(chuàng)建白色背景
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
// 設(shè)置文字樣式
$font_size = 20;
$font_color = imagecolorallocate($image, 0, 0, 0);
$font_file = 'arial.ttf'; // 字體文件路徑
// 添加文字
$angle = 0; // 文字角度
imagettftext($image, $font_size, $angle, 50, 50, $font_color, $font_file, 'Hello, World!');
// 輸出圖片
header('Content-Type: image/jpeg');
imagejpeg($image);
// 釋放資源
imagedestroy($image);
?>
注意事項(xiàng)
- 字體文件:確保字體文件路徑正確,且PHP有權(quán)限訪問。
- 文字位置:調(diào)整
imagettftext()
函數(shù)的坐標(biāo)參數(shù)以改變文字位置。 - 文字大小:根據(jù)需要調(diào)整
imagettftext()
函數(shù)的$font_size
參數(shù)。
高級(jí)應(yīng)用
多行文字
$height = imagettfbbox($font_size, $angle, $font_file, 'Hello, World!')[5];
$line_height = $height[1] - $height[7];
$line_count = ceil(strlen('Hello, World!') / $font_size);
for ($i = 0; $i < $line_count; $i++) {
imagettftext($image, $font_size, $angle, 50, $i * $line_height + 50, $font_color, $font_file, 'Hello, World!');
}
文字陰影
$shadow_color = imagecolorallocate($image, 100, 100, 100);
imagettftext($image, $font_size, $angle, 60, 60, $shadow_color, $font_file, 'Hello, World!');
imagettftext($image, $font_size, $angle, 50, 50, $font_color, $font_file, 'Hello, World!');