PHP使用GD创建简单的4位验证码

<?php
// $width=100;
// $height=30;


//创建画布
$image=imagecreatetruecolor(100,30);
//创建颜色
$white=imagecolorallocate($image,255,255,255);
//整幅画板使用imagecolorallocate创建出来的颜色进行填充0,0代表整幅图
//官方解释:
//imagefill() 在 image 图像的坐标 x,y(图像左上角为 0, 0)处用 color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。
imagefill($image, 0, 0, $white);
//彩色4位的数字验证码
for($i=0;$i<4;$i++){
  $fontsize=5;
  //x代表横轴,注意总宽度只有100,所以4位验证码,一个占用25,用$i再加上随机数来改变每次数字出现的位置
  //如果没有$i,每次四个数字都会出现在都在25加上5-10之间的一个数,如果有$i,就是25,50,75,100,再加上5-10之间
  //的数,这样四个验证码的位置既不会每次都在25,50,75,100上,也不会重叠。
  $x=($i*100/4)+mt_rand(5,10);
  //y代表纵轴,表示验证码横向出现的位置高低
  $y=mt_rand(5,10);
  //str表示出现的数字在0-9之间的随机数
  $str=mt_rand(0,9);
  //创建颜色,这里的颜色要深一点,防止被点和线覆盖
  $color=imagecolorallocate($image,mt_rand(0,120),mt_rand(0,120),mt_rand(0,255));
  //输出字符,
  imagestring($image,$fontsize,$x,$y,$str,$color);
}
//创建验证码图片中的小点,$i<200代表出现200个点
for($i=0;$i<200;$i++){
  //创建颜色,这里的颜色要浅一点,防止盖住验证码
  $color=imagecolorallocate($image,mt_rand(120,150),mt_rand(110,180),mt_rand(80,100));
  //创建点
  imagesetpixel($image,mt_rand(0,100),mt_rand(0,30),$color);
}
//创建四条横线
for($i=0;$i<4;$i++){
  //创建颜色,这里的颜色要浅一点,防止盖住验证码
  $color=imagecolorallocate($image,mt_rand(80,130),mt_rand(110,160),mt_rand(90,190));
  //画4条线,一条线是两个点组成的,所以这里的xy有两个
  imageline($image,mt_rand(0,99),mt_rand(5,30),mt_rand(0,99),mt_rand(0,30),$color);
}
//告诉浏览器要输出图片
header('content-type:image/png');
//输出png格式的图
imagepng($image);
//销毁图像
imagedestroy($image);

猜你喜欢

转载自blog.csdn.net/weixin_38468437/article/details/79990480
今日推荐