<?php
	class Vcode{
		private $image;
		private $width;
		private $height;
		private $codeNumber;
		private $fontSize;
		private $ttf;
		public $code;				//		<--		调用此属性获取验证码字符串
		
		/**
		*	此类可以无需传任何参数,直接调用 display()方法即可
		*	调用code属性获得验证码字符串,用于验证验证码是否正确
		*
		*	@param $codeNumber	int		验证码的个数
		*	@param $height		int		验证码的高度
		*	@param $fontSize	int		验证码字体大小
		*
		*/
		function __construct($ttf = 'arial.ttf',$codeNumber = '4',$height = '30',$fontSize = '16'){
			$this->ttf = $ttf;
			$this->codeNumber = $codeNumber;
			$this->fontSize = $fontSize;
			$this->width = $this->fontSize*$this->codeNumber;
			$this->height = $height;
		}
		
		/**
		*	调用方法输出验证码,无参数
		*/
		public function display(){
			$this->createImage();
			$this->disturb();
			$this->imageText();
			$this->outImage();
		}
		
		//创建并填充画布
		private function createImage(){
			$this->image = imagecreatetruecolor($this->width,$this->height);
			$color = imagecolorallocate($this->image,rand(220,255),rand(220,255),rand(220,255));
			imagefill($this->image,0,0,$color);
			return $this->image;
		}
		
		//为画布添加干扰元素
		private function disturb(){
			//点
			for ($i = 0; $i < 100; $i++){
				$color = imagecolorallocate($this->image,rand(0,250),rand(0,250),rand(0,250));
				imagesetpixel($this->image,rand(0,$this->width),rand(0,$this->height),$color);
			}
			
			//线
			for ($i = 0; $i < 30; $i++){
				$color = imagecolorallocate($this->image,rand(0,200),rand(0,200),rand(0,200));
				imageline($this->image,rand(0,$this->width),rand(0,$this->height),rand(0,$this->width),rand(0,$this->height),$color);
			}
		}
		
		//添加文字
		private function imageText(){
			$string = "QWERTYUOPASDFGHJJJKZXCVBNMqwertyuopasdfghjkzxcvbnm234567890";
			$str = substr(str_shuffle($string),0,$this->codeNumber);
			for ($i = 0; $i < strlen($str); $i++){
				$color = imagecolorallocate($this->image,rand(0,70),rand(0,70),rand(0,70));
				imagettftext($this->image,$this->fontSize,rand(0,20),$this->fontSize*$i+1,floor($this->height*(23/30)),$color,$this->ttf,$str{$i});
			}
			return $this->code = $str;
		}
		
		//输出图像
		private function outImage(){
			header("content-type:image/png");
			imagepng($this->image);
		}		
	}