php实现验证码
代码展示
<?php
header('content-type:image/png;charset=utf-8');

/*创建图像*/
$width = 120;
$height = 40;
$img = imagecreatetruecolor($width, $height);

/*绘制图像*/

//分配颜色
$color1 = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
$color2 = imagecolorallocate($img, 8, 8, 8);
$color3 = imagecolorallocate($img, 0, 0, 0);

//为图像填充随机背景色
imagefill($img, 0, 0, $color1);

//画像素点
for ($i = 0; $i < 100; $i++) {
  imagesetpixel($img, rand(0, $width - 1), rand($height - 1, 0), $color2);
}

// 画线条
for ($i = 0; $i < 3; $i++) {
  imageline($img, rand(0, $width / 2), rand(0, $height), rand($width / 2, $width), rand(0, $height), $color2);
}

//用 TrueType 字体向图像写入文本
$strArr = array(
  'A', 'B' . 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
);
$string = '';
for ($i = 0; $i < 5; $i++) {
  $string .= $strArr[rand(0, count($strArr) - 1)];
}
imagettftext($img, 18, 0, rand(0, 26), rand(20, 40), $color3, 'font/SketchyComic.ttf', $string);


/*输出图像*/
imagepng($img); // 以 PNG 格式将图像输出到浏览器或文件

/*销毁图像*/
imagedestroy($img);


效果展示

最后修改:2024 年 02 月 24 日
如果你觉得作者像乞讨的,你可以随意打赏他一点。