在網頁開發中,有時我們希望動態生成帶有漂亮陰影效果的文本圖像,用於按鈕、標題或水印。幸運的是,PHP的GD庫提供了強大的圖像處理功能,其中imagecolorallocatealpha()函數可以幫助我們定義帶有透明度的顏色,從而輕鬆繪製帶透明陰影的文字。
本文將逐步講解如何使用imagecolorallocatealpha()函數製作一個帶透明陰影效果的文本圖像。
首先,我們需要創建一個圖像畫布。這裡我們使用imagecreatetruecolor()函數創建一個真彩色圖像。
<?php
// 創建寬 400px,高 100px 的畫布
$width = 400;
$height = 100;
$image = imagecreatetruecolor($width, $height);
// 設置背景顏色(白色)
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
為了讓PNG 圖像的透明部分正確顯示,我們需要關閉混合模式,並啟用保存alpha 通道。
// 關閉混合模式
imagealphablending($image, false);
// 啟用 alpha 保持
imagesavealpha($image, true);
imagecolorallocatealpha()函數的參數是(image, red, green, blue, alpha) ,其中alpha取值範圍是0(完全不透明)到127(完全透明)。
例如,我們定義一個黑色半透明的陰影:
// 定義黑色半透明陰影
$shadow_color = imagecolorallocatealpha($image, 0, 0, 0, 60);
注意:這裡的60表示大約一半透明的效果。
我們使用imagettftext()函數來繪製文字,需要指定字體文件路徑。
// 字體文件路徑(請根據實際情況調整)
$font = __DIR__ . '/arial.ttf';
$text = 'Hello, m66.net!';
$font_size = 24;
// 繪製陰影(稍微偏移幾個像素)
imagettftext($image, $font_size, 0, 22, 62, $shadow_color, $font, $text);
// 繪製主文字(黑色)
$text_color = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, $font_size, 0, 20, 60, $text_color, $font, $text);
最後,我們將圖像輸出為PNG 格式,並釋放資源。
// 設定 header
header('Content-Type: image/png');
// 輸出圖像
imagepng($image);
// 釋放內存
imagedestroy($image);
?>
<?php
$width = 400;
$height = 100;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
imagealphablending($image, false);
imagesavealpha($image, true);
$shadow_color = imagecolorallocatealpha($image, 0, 0, 0, 60);
$text_color = imagecolorallocate($image, 0, 0, 0);
$font = __DIR__ . '/arial.ttf';
$text = 'Hello, m66.net!';
$font_size = 24;
imagettftext($image, $font_size, 0, 22, 62, $shadow_color, $font, $text);
imagettftext($image, $font_size, 0, 20, 60, $text_color, $font, $text);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
字體文件<br> 上述代碼使用了arial.ttf字體文件,請確保該字體文件存在於腳本所在目錄,或修改為你服務器上的其他字體路徑
透明度調整
alpha參數可根據需要調整。如果要更透明,可以使用更大的值(接近127);如果要更不透明,可以用更小的值。
部署建議<br> 部署時,請確保服務器的PHP 配置中啟用了GD 庫,否則代碼將無法運行