使用画布生成验证码

首先我们先创建一个字符串,并放好要生成验证码的字符,其中我们去掉了不容易识别的i,l,o ,I,L,O

//字符串,去掉不容易识别的i,l,o ,I,L,O
$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";

然后我们再创建一个大小合适的画布填充一个颜色并输出

<?php
//案例:生成验证码
header('content-type:image/png');
//字符串,去掉不容易识别的i,l,o ,I,L,O
$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";

//创建画
$width = 200;
$height = 100;
$img = imagecreatetruecolor($width,$height);

//颜色
$color = imagecolorallocate($img,0xcc,0xcc,0xcc);
//填充
imagefill($img,0,0,$color);

//输出画布
imagepng($img);

//销毁画布
imagedestroy($img);


然后我们再来画噪点,我们让它随机生成100个噪点,位置随机,颜色也随机生成

//画噪点
for($i=0;$i<100;$i++){
    $color=imagecolorallocate($img,rand(0,100),rand(0,100));
    $x=rand(0,$width);
    $y=rand(0,$height);
    imagesetpixel($img,$x,$y, $color);
}


画完噪点我们再来画噪线,噪线要画的少一些,我们随机生成30个噪线,位置随机,颜色也随机

//画噪线
for($i=0;$i<30;$i++){
    $color=imagecolorallocate($img,rand(0,100),rand(0,100));
    $x1=rand(0,$width);
    $y1=rand(0,$height);
    $x2=rand(0,$width);
    $y2=rand(0,$height);
    imageline($img,$x1,$y1,$x2,$y2,$color)
}


画完噪点,噪线我们就可以生成验证码了,生成4位的验证码,我们就需要循环四次,
首先我们要获得整个字符串的长度,$len = strlen($str); 然后我们来生成随机数,$index = rand(0,$len-1);然后我们去取出它的字符,我们从index的位置取,取一个.$chr = substr($str,$index,1);

//画文字
$len = strlen($str);
$font = "simsunb.ttf";
for($i=0;$i<4;$i++){
    $color=imagecolorallocate($img,255,0,0);
    $index = rand(0,$len-1);
    $chr = substr($str,$index,1);
    $x = 20+$i*50;
    $y=80;

    imagettftext($img,40,rand(-70,70),$x,$y,$font,$chr);
}

然后我们根据画布大小来调整好验证码的大小和位置,完整版代码如下
 

<?php
//案例:生成验证码
header('content-type:image/png');
//字符串,去掉不容易识别的i,l,o ,I,L,O
$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";

//创建画
$width = 200;
$height = 100;
$img = imagecreatetruecolor($width,$height);

//颜色
$color = imagecolorallocate($img,0xcc,0xcc,0xcc);
//填充
imagefill($img,0,0,$color);

//画噪点
for($i=0;$i<100;$i++){
    $color=imagecolorallocate($img,rand(0,100),rand(0,100));
    $x=rand(0,$width);
    $y=rand(0,$height);
    imagesetpixel($img,$x,$y, $color);
}
//画噪线
for($i=0;$i<30;$i++){
    $color=imagecolorallocate($img,rand(0,100),rand(0,100));
    $x1=rand(0,$width);
    $y1=rand(0,$height);
    $x2=rand(0,$width);
    $y2=rand(0,$height);
    imageline($img,$x1,$y1,$x2,$y2,$color)
}

//画文字
$len = strlen($str);
$font = "simsunb.ttf";
for($i=0;$i<4;$i++){
    $color=imagecolorallocate($img,255,0,0);
    $index = rand(0,$len-1);
    $chr = substr($str,$index,1);
    $x = 20+$i*50;
    $y=80;

    imagettftext($img,40,rand(-70,70),$x,$y,$font,$chr);
}
//输出画布
imagepng($img);

//销毁画布
imagedestroy($img);

猜你喜欢

转载自blog.csdn.net/qq_42402975/article/details/84524902