font=root_path.'/font/elephant.ttf'; } //创建4个随机码 private function createcode(){ $_leng=strlen($this->charset); for($i=1;$icodelen;$i++){ $this->code.=$this->charset[mt_rand(0,$_leng)]; } return $this->code; } //创建背景 private function createbg(){ //创建画布 给一个资源jubing $this->img=imagecreatetruecolor($this->width,$this->height); //背景颜色 $color=imagecolorallocate($this->img,mt_rand(157,255),mt_rand(157,255),mt_rand(157,255)); //画出一个矩形 imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color); } //创建字体 private function createfont(){ $_x=($this->width / $this->codelen); //字体长度 for ($i=0;$icodelen;$i++){ //文字颜色 $color=imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156)); //资源句柄 字体大小 倾斜度 字体长度 字体高度 字体颜色 字体 具体文本 imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height/1.4,$color,$this->font,$this->code[$i]); } } //随机线条 private function createline(){ //随机线条 for ($i=0;$i $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156)); imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color); } //随机雪花 for ($i=0;$i $color = imagecolorallocate($this->img,mt_rand(220,255),mt_rand(220,255),mt_rand(220,255)); imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color); } } //输出背景 private function output(){ //生成标头 header('contenttype:img/png'); //输出图片 imagepng($this->img); //销毁结果集 imagedestroy($this->img); } //对外输出 public function doimg(){ //加载背景 $this->createbg(); //加载文件 $this->createcode(); //加载线条 $this->createline(); //加载字体 $this->createfont(); //加载背景 $this->output(); } //获取验证码 public function getcode(){ return strtolower($this->code); } } ?>
复制代码
调用示例:index.php 为大家推荐几篇有关php验证码的文章:php随机验证码 php生成随机验证码(图文)用php生成带有雪花背景的验证码php写的一个验证码php生成动态图片验证码的一段代码