码迷,mamicode.com
首页 > 其他好文 > 详细

生成验证码

时间:2016-06-30 19:49:03      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 生成验证码
 */
//设置文件头为图片输出

header("Content-type:image/JPEG");

//调用生成验证码函数
$checkcode = make_rand(4);

/*
*生成验证码字符
*@param int $length 验证码字符长度
*@return string
 */
function make_rand($length = "32") {
    $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $result = "";
    for($i=0;$i<$length;$i++) {
        $num[$i] = rand(0,25);
        $result .= $str[$num[$i]];
    }

    return $result;
}
//调用输出验证码图片函数
getAuthImage($checkcode,160,40);
/*
*生成验证码图片
*@param string $text 验证码字符
 */
function getAuthImage($text,$w,$y) {
    //设置图片的宽度和高度
    $im_x = $w;
    $im_y = $y;
    //创建图片
    $im = imagecreatetruecolor($im_x, $im_y);
    $text_c = imagecolorallocate($im, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100));
    $tmpC0 = mt_rand(100,255);
    $tmpC1 = mt_rand(100,255);
    $tmpC2 = mt_rand(100,255);
    $buttum_c = imagecolorallocate($im, $tmpC0, $tmpC1, $tmpC2);
    imagefill($im,16,13,$buttum_c);//改变背景颜色

    //字体文件
    $font = ‘arial.ttf‘;
    for($i=0;$i<strlen($text);$i++) {
        $tmp = substr($text, $i,1);
        $array = array(-1,1);
        $p = array_rand($array);
        $an = $array[$p]*mt_rand(1,10);//角度
        $size = 28;
        imagettftext($im,$size,$an,15+$i*$size,35,$text_c,$font,$tmp);
    }

    //将字符写入文件中
    $distortion_im = imagecreatetruecolor($im_x, $im_y);
    imagefill($distortion_im,16,13,$buttum_c);
    for($i=0;$i<$im_x;$i++) {
        for($j=0;$j<$im_y;$j++) {
            $rgb = imagecolorat($im, $i, $j);
            if( (int)($i+20+sin($j/$im_y*2*M_PI)*10) <= imagesx($distortion_im) && (int)($i+20+sin($j/$im_y*2*M_PI)*10)>=0) {
                imagesetpixel($distortion_im, (int)($i+10+sin($j/$im_y*2*M_PI-M_PI*0.1)*4), $j, $rgb);
            }
        }
    }

    //干扰元素点的数量
    $count = 160;
    //创建干扰元素点
    for($i=0;$i<$count;$i++) {
        $randcolor = imagecolorallocate($distortion_im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
        imagesetpixel($distortion_im, mt_rand()%$im_x, mt_rand()%$im_y, $randcolor);
    }

    //创建干扰线条
    $rand = mt_rand(5,30);
    $rand1 = mt_rand(15,25);
    $rand2 = mt_rand(5,10);
    for($yy=$rand;$yy<=+$rand+2;$yy++) {
        for($px=-80;$px<=80;$px=$px+0.1) {
            $x=$px/$rand1;
            if($x!=0) {
                $y=sin($x);
            }
            $py=$y*$rand2;
            imagesetpixel($distortion_im, $px+80, $py+$yy, $text_c);
        }
    }
    //以PNG格式将图像输出到浏览器
    ImagePNG($distortion_im);

    //销毁图像
    imagedestroy($distortion_im);
    imagedestroy($im);
}

生成验证码

标签:

原文地址:http://www.cnblogs.com/lilyhomexl/p/5630934.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!