PHP原生语言 生成验证码图片

用纯php语言生成一张验证码图片
$img_w=60;      //初始化验证码图片宽度
$img_h=22;      //初始化验证码图片高度
$char_len=5;    //验证码码值长度
$font=20;       //验证码码值的字体大小
$char=array_merge(range('A','Z'),range('a','z'),range(1,9));//生成码值数组
$rand_keys=array_rand($char,$char_len);//随即获取$char_len个码值的键
if($char_len==1) {                     //判断当码值长度为1时,将其放入数组
    $rand_keys=array($rand_keys);
}
shuffle($rand_keys);//打乱随即获取的码值键的数组
$code='';//根据键获取对应的码值,并拼接成字符串
foreach($rand_keys as $key) {
    $code .=$char[$key];
}
@session_start();//将获取的码值字符串保存到Session中
$_SESSION['captcha_code']=$code;
$img=imagecreatetruecolor($img_w,$img_h);          //生成画布
$bg_color=imagecolorallocate($img,0xcc,0xcc,0xcc); //为画布分配颜色
imagefill($img,0,0,$bg_color);                     //设置画布背景色
for($i=0;$i<=300;++$i) { //为验证码图片生成多个干扰点
    $color=imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));//随机为画布分配颜色
    imagesetpixel($img,mt_rand(0,$img_w),mt_rand(0,$img_h),$color);//在$img图像上随机绘制一个点
}
$rect_color=imagecolorallocate($img,0xff,0xff,0xff);//为验证码边框分配颜色
imagerectangle($img,0,0,$img_w-1,$img_h-1,$rect_color);//绘制验证码图片边框
$str_color=imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));//设定字符串颜色
$font_w=imagefontwidth($font);//根据设定的字体获取单个字符的宽和高
$font_h=imagefontheight($font);
$str_w=$font_w*$char_len;//验证码的码值总宽度=单个字符宽度*字符个数
imagestring($img,$font,($img_w-$str_w)/2,($img_h-$font_h)/2,$code,$str_color);//将码值写入验证码图片中
header('Content-Type:image/png'); //设置输出验证码图片的格式
imagepng($img);//输出验证码
imagedestroy($img);//销毁画布
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值