您好,欢迎访问一九零五行业门户网

php图片验证码函数实现扭曲字符的实现代码

/**
* captchaimage() - 创建扭曲字符的验证码图片* $session_name string 验证码图片创建时所需生成session的变量名* $width int 验证图片的宽度,默认120,注:图片高度与宽度比例相对固定* $noise int 干扰素的点数,默认0* $disturb int 干扰字符个数,默认0* $curve bool 是否增加干扰曲线,默认ture* */function captchaimage($session_name = '', $width = 120, $noise = 0, $disturb = 0, $curve = true){ $im_x = $width; $im_y = ceil(0.25 * $width); $im = imagecreatetruecolor($im_x, $im_y); $text_c = imagecolorallocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100)); $gray_rand = mt_rand(160, 220); $buttum_c = imagecolorallocate($im, $gray_rand, $gray_rand, $gray_rand); imagefill($im, 0, 0, $buttum_c);session_start();
$text = '';$characters = 'abcefghjklmnpqrstuvwxyz';for($i = 0, $len = strlen($characters); $i $text .= $characters{rand(0, $len - 1)};if(isset($session_name{0}) && session_start()){ $_session[$session_name] = $text; $_session['captchasessiontime'] = time();}}$font = 'arial.ttf';
$size = floor(0.2 * $width);$ttfbox = imagettfbbox($size, 0, $font, $text);
$text_width = abs($ttfbox[2] - $ttfbox[0]);$side = floor(($im_x - $text_width) / 2);$array = array(-1, 1);
for ($i = 0; $i $p = array_rand($array);$an = $array[$p] * mt_rand(5, 10); // 字符倾斜角度imagettftext($im, $size, $an, $side + $i * ($size - 1), $im_y - 3, $text_c, $font, $text{$i});}$distortion_im = imagecreatetruecolor ($im_x, $im_y);
imagefill($distortion_im, 0, 0, $buttum_c);$distortion = floor(0.04 * $width); // 扭曲程度for ($i = 0; $i for ($j = 0; $j $rgb = imagecolorat($im, $i , $j);if( (int)($i + sin($j / $im_y * 2 * m_pi) * $distortion) = 0 ){imagesetpixel($distortion_im, (int)($i + sin($j / $im_y * 2 * m_pi - m_pi * 0.1) * $distortion) , $j, $rgb);}}}if($disturb > 0){
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';for($i = 0; $i imagestring($distortion_im, 3, mt_rand(-10, $im_x), mt_rand(-10, $im_y), $chars[mt_rand(0, 35)], $text_c);}}//加入干扰象素;
if($noise > 0){for($i = 0; $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);}}// 加干扰曲线
if($curve){$rand = mt_rand(5, 30);$rand1 = mt_rand(15, 25);$rand2 = mt_rand(5, 10);for ($yy = $rand; $yy for ($px = -60; $px $x = $px / $rand1;$y = ($x != 0) ? sin($x) : $y;$py = $y * $rand2;imagesetpixel($distortion_im, $px + 60, $py + $yy, $text_c);}}}//设置文件头;
header(content-type: image/jpeg);//以png格式将图像输出到浏览器或文件;
imagepng($distortion_im);//销毁一图像,释放与image关联的内存;
imagedestroy($distortion_im);imagedestroy($im);}captchaimage('code', 100); //生成一张图片 并将随机数字存放到key为code的session中
复制代码
其它类似信息

推荐信息