在网页开发中,有时我们希望动态生成带有漂亮阴影效果的文本图像,用于按钮、标题或水印。幸运的是,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);
?>
字体文件
上述代码使用了 arial.ttf 字体文件,请确保该字体文件存在于脚本所在目录,或修改为你服务器上的其他字体路径。
透明度调整
alpha 参数可根据需要调整。如果要更透明,可以使用更大的值(接近 127);如果要更不透明,可以用更小的值。
部署建议
部署时,请确保服务器的 PHP 配置中启用了 GD 库,否则代码将无法运行。