<?php
header("Content-Type: image/png");//设定文档类型
session_start();
$width = 50; //验证码图片的宽度
$height = 20; //验证码图片的高度
$length = 4; //验证码的位数
/**
* 生成字符串形式验证码
* 通过随机数在候选字符列表中组合出随机验证码
*/
function createCaptcha($size){
$codeList = "abcdefghigkmnpqrstuvwxyz23456789"; //为什么没有0、1、o、l? 容易混淆
$captcha = '';
for($i=0; $i<$size; $i++){
$randomNum = mt_rand(0,31);
$captcha .= $codeList[$randomNum];
}
return $captcha;
}
/**
* 将字符串验证码生成为图片形式
*
* @return: resource 生成图片的资源
*/
function createImage($captcha, $width, $height){
$length = strlen($captcha);
$size = $width/$length; //每个字符的宽度
$left = 0;
$imageResource = imagecreate($width,$height); //生成指定宽高的空白图片
$bgColor = imagecolorallocate($imageResource,169,169,169); //设定颜色,第一次调用此函数会给图片填充背景颜色
$strColor = imagecolorallocate($imageResource,0,0,0); //分配字符串的颜色
/*
* for()
* 依次把每个字符写入到图片中
* 每个字符的大小随机
* 每个字符的角度随机
*/
for($i=0; $i<$length; $i++){
$randomSize = mt_rand($size-$size/10,$size+$size/10); //随机生成文字的大小
$location = $left+$i*$size+$size/10; //计算字符的位置
imagettftext($imageResource,$randomSize,mt_rand(-18,18),$location,15,$strColor,'./ariblk.ttf',$captcha[$i]); //将字符写入图片
}
/*
* for()
* 向图片添加干扰点
* 干扰点的颜色随机产生
*/
for($i=0; $i<50; $i++){
$randomColor = imagecolorallocate($imageResource,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
imagesetpixel($imageResource,mt_rand(0,$width),mt_rand(0,$height),$randomColor);
}
return $imageResource;
}
$captcha = createCaptcha($length); //生成字符验证码
$_SESSION['captcha'] = $captcha; //保存字符验证码
$image = createImage($captcha,$width,$height); //创建图片验证码
imagepng($image);//生成图片
imagedestory($image);//销毁图片,释放内存
?>
<?php
$im = imagecreatefrompng("test.png");
imagepng($im);
?>
<?php
$im = imagecreatefrompng("test.png");
imagepng($im);
?>