\(^o^)/~
现在网上越来越离不开验证码了,不知道小伙伴们知不知利用php的GD库就可以生成验证码,Σ(⊙▽⊙"a ......
首先介绍几个需要用的函数。
1.imagesetpixel()
这个函数可以进行像素点的绘制,在验证码中,我们称之为“噪点”,简直是一个神器。不知道小伙伴有没有想起来验证码上的点点呢,就是用这个函数生成的。
2.str_shuffle()
利用这个打乱字符串,然后利用substr()截取给定的位数,就可以生成一个随机字符串啦。
实例:
<?php $img = imagecreatetruecolor(, );
$black = imagecolorallocate($img, 0x00, 0x00, 0x00);
$green = imagecolorallocate($img, 0x00, 0xFF, 0x00);
$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);
imagefill($img, , , $white);
//生成随机的验证码
$code = make();
imagestring($img, , , , $code, $black);
//加入噪点干扰
for ($i = ; $i < ; $i++) {
imagesetpixel($img, rand(, ), rand(, ), $black);
imagesetpixel($img, rand(, ), rand(, ), $green);
}
//加入线段干扰
for ($n = ; $n <= ; $n++) {
imageline($img, , rand(, ), , rand(, ), $black);
imageline($img, , rand(, ), , rand(, ), $white);
}
//输出验证码
header("content-type: image/png");
imagepng($img);
//销毁图片
imagedestroy($img);
//生产随机验证码的函数
function make($length)
{
$code = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return substr(str_shuffle($code), , $length);
}
效果: