PHP常用类------生成验证码类Code
直接附上代码吧!很简单的代码,写一遍基本就会了,主要明白用GD库画图的几个步骤:
1.先创建画布,不然画在哪儿?(imagecreatetruecolor)
2.根据要画的数据,选定颜色 (imagecolorallocate)
3.颜色有了,该考虑画啥了,画圆形,矩形,还是扇形,你喜欢就OK!
4.用什么画(系统中提供很多函数,比如imagerectangle,imagearc)
5.画完之后,有三个选择,最简单的,就是什么也不做;另外两个选择就是显示或保存,可以同时做(imagepng,imagegif)
6.图用完之后,就该释放资源了,有始有终嘛(imagedestroy)
代码如下:
<?php /** * 该类实例化的时候需要3个参数 * $width;//验证码的宽,默认值为80px * $height;//验证码的高,默认值为20px * $num;//验证码字符的个数,默认值为4 */ class Code{ private $width;//验证码的宽 private $height;//验证码的高 private $num;//验证码字符的个数 private $code;//验证码的字符串 private $img;//验证码source function __construct($width=80,$height=20,$num=4){ $this->width=$width; $this->height=$height; $this->num=$num; $this->code=$this->create_code(); } private function create_canvas(){//创建画布 $this->img=imagecreatetruecolor($this->width,$this->height); $background_color=imagecolorallocate($this->img,0xFF,0xFF,0xFF); imagefill($this->img,0,0,$background_color); $border_color=imagecolorallocate($this->img,0xAA,0xAA,0xAA); imagerectangle($this->img,0,0,$this->width-1,$this->height-1,$border_color); } private function create_code(){//生成验证码的字符串 $src="3456789qwertyupkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM"; $code=""; for($i=0;$i<$this->num;$i++){ $index=mt_rand(0,strlen($src)-1); $code.=$src[$index]; } return $code; } private function paint_char(){//将生成的字符串画在画布上 for($i=0;$i<$this->num;$i++){ $char_color=imagecolorallocate($this->img,0xFF,0,0xFF); $font_size=4; $x=5+($this->width/$this->num)*$i; $y=($this->height-imagefontheight($font_size))/2; imagechar($this->img,$font_size,$x,$y,$this->code[$i],$char_color); } } private function add_disturbance(){//添加干扰标记 for($i=0;$i<20;$i++){ $color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); imagesetpixel($this->img,rand(1,$this->width-2),rand(1,$this->height-2),$color); } } private function print_code() {//判断兼容哪种格式 if (imagetypes() & IMG_PNG) { header("Content-type: image/png"); imagepng($this->img); } elseif (imagetypes() & IMG_JPG) { header("Content-type: image/jpeg"); imagejpeg($this->img); } else { die("No image support in this PHP server"); } } private function get_code(){//获取验证码字符串的值 return $this->code; } private function destroy_code(){//释放资源 imagedestroy($this->img); } function show_image_code(){//所有步骤的汇集,搞定所有验证码的工作 $this->create_canvas(); $this->paint_char(); $this->add_disturbance(); $this->print_code(); $this->destroy_code(); } } //测试 $code = new Code(80, 30, 4); $code->show_image_code(); ?>
如需转载,请注明文章出处,谢谢!!!