验证码核心

<?php

// 1, 创建画布
$img = imagecreatetruecolor(170, 40);

// 2, 填充背景色
// 2.1 创建背景色句柄
$backcolor = imagecolorallocate($img, mt_rand(200, 255), mt_rand(150, 255), mt_rand(200, 255));
// 2.2 填充背景
imagefill($img, 0, 0, $backcolor);

// 3, 产生随机验证码字符串
// 3.1,拼凑出一个数组,里面有大小写英文字母和数字(range和array_merge)
$arr = array_merge(range('A','Z'),range('a','z'),range(0,9));
// 3.2,打乱该数组(shuffle)
shuffle($arr);
// 3.3,利用array_rand随机获取若干个该数组的下标(键)
$rand_keys = array_rand($arr,4);
// 3.4,依次根据数组的键获得数组的值,拼凑到一起(foreach遍历)
$str = '';
foreach($rand_keys as $value) {
    $str .= $arr[$value];// $rand_keys中的值$value就是原数组$arr中的键
}

// 4,将验证码字符串写到图片上面
// 4.1 计算字符间隔
$span = ceil(170/(4+1));
for($i=1;$i<=4;$i++) {
    $strcolor = imagecolorallocate($img, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
    imagestring($img, 5, $i*$span, 10, $str[$i-1], $strcolor);
}

// 5, 添加干扰线
for($i=1;$i<=6;$i++) {
    $linecolor = imagecolorallocate($img, mt_rand(50, 100), mt_rand(50, 100), mt_rand(0, 100));
    imageline($img, mt_rand(0,169), mt_rand(0,39), mt_rand(0,169), mt_rand(0,39), $linecolor);
}

// 6, 添加干扰点(噪点)
for($i=1;$i<=170*40*0.03;$i++) {
    $pxcolor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imagesetpixel($img, mt_rand(0,169), mt_rand(0,39), $pxcolor);
}


// 7, 输出图片
header("Content-type:image/png");
// 清理数据缓冲区
ob_clean();
imagepng($img);

posted @ 2016-12-08 01:10  echopp  阅读(140)  评论(0编辑  收藏  举报