在Web开发中,验证码图像常用于防止自动提交表单。PHP 提供了丰富的图像处理函数来生成验证码图像。其中,imagecreatefromgd2() 是一个用于从 GD2 文件创建图像资源的函数,但它通常用于读取已有的图像资源,而不是直接生成图像。不过,我们可以结合 imagegd2() 函数将动态生成的图像保存为 GD2 格式,再通过 imagecreatefromgd2() 读取后处理。
本文将演示如何动态生成一个带有随机文本的验证码图像,并使用 imagecreatefromgd2() 读取处理该图像。
创建一个图像资源
添加背景色和随机验证码文字
保存为 .gd2 格式
读取 .gd2 文件并输出为最终图像
<?php
// Step 1: 动态创建验证码图像
$width = 150;
$height = 50;
$image = imagecreatetruecolor($width, $height);
// 设置背景色
$bgColor = imagecolorallocate($image, 255, 255, 255); // 白色
imagefill($image, 0, 0, $bgColor);
// 设置文本颜色
$textColor = imagecolorallocate($image, 0, 0, 0); // 黑色
// 生成随机验证码内容
$captcha = '';
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
for ($i = 0; $i < 6; $i++) {
$captcha .= $chars[rand(0, strlen($chars) - 1)];
}
// 添加文字到图像
$fontSize = 5; // 1 到 5 的字体大小
$x = 10;
$y = ($height - imagefontheight($fontSize)) / 2;
imagestring($image, $fontSize, $x, $y, $captcha, $textColor);
// Step 2: 保存图像为 .gd2 文件
$gd2Path = 'captcha.gd2';
imagegd2($image, $gd2Path);
// 销毁原始图像资源
imagedestroy($image);
// Step 3: 使用 imagecreatefromgd2 读取图像
$gd2Image = imagecreatefromgd2($gd2Path);
// 设置 HTTP 头输出图像
header('Content-Type: image/png');
imagepng($gd2Image);
// 清理
imagedestroy($gd2Image);
?>
请确保 PHP 安装时启用了 GD 库(一般默认启用)。
文件保存路径 captcha.gd2 应有写入权限。
你可以将验证码内容保存在 $_SESSION 中,以用于后续验证。
你可以在表单中嵌入这个动态生成的验证码图像:
<form method="post" action="https://m66.net/verify.php">
<img src="https://m66.net/captcha.php" alt="验证码">
<input type="text" name="captcha" placeholder="请输入验证码">
<input type="submit" value="提交">
</form>
虽然 imagecreatefromgd2() 并不直接用于创建图像,但通过先使用 imagegd2() 生成 GD2 文件,再读取并输出,可以达到动态生成验证码图像的目的。这种方式适用于需要中间图像缓存或图像模板的场景。
如需更复杂的验证码图像(扭曲、干扰线、字体变化等),可以使用 imagettftext() 函数结合 TTF 字体实现更多高级功能。
需要我演示一个带 TTF 字体的验证码版本吗?