<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/8/25 0025
* Time: 18:16
*/
class Code{
protected $number;
protected $type;
protected $width;
protected $height;
protected $code;
protected $image;
public function __construct($number = 4,$type = 3,$width= 200,$height = 60){
$this->number = $number;
$this->type = $type;
$this->width = $width;
$this->height = $height;
$this->code = $this->createCode();
}
protected function createCode(){
switch($this->type){
case 1:
$code = $this->createNumberCode();
break;
case 2:
$code = $this->createStrCode();
break;
case 3:
$code = $this->createStrNumberCode();
break;
default:
break;
}
return $code;
}
protected function createNumberCode(){
$str = join('',range(0,9));
return substr(str_shuffle($str),0,$this->number);
}
protected function createStrCode()
{
$str = join('', range('a', 'z'));
$str = substr(str_shuffle($str.strtoupper($str)),0,$this->number);
return $str;
}
protected function createStrNumberCode(){
$number = join('',range(0,9));
$str = join('',range('a','z'));
return substr(str_shuffle($number.$str.strtoupper($str)),0,$this->number);
}
public function __get($name){
if($name == 'code'){
return $this->code;
}else{
return false;
}
}
public function outPutImage(){
$this->createImage();
//添加背景色
$this->fillImage();
// 将验证码填充进去
$this->drawChar();
header('Content-Type:image/png');
imagepng($this->image);
// 添加干扰元素
//$this->drawalDisturbe();
// 输出
// $this->show();
}
protected function fillImage(){
imagefill($this->image,0,0,$this->lightColor());
}
protected function lightColor(){
return imagecolorallocate($this->image,mt_rand(130,255),mt_rand(130,255),mt_rand(130,255));
}
protected function darkColor(){
return imagecolorallocate($this->image,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
}
protected function drawChar(){
$width = ceil($this->width/$this->number);
for($i = 0;$i<$this->number;$i++){
$x = mt_rand( $i* $width +5,($i+1)*$width -10);
$y = mt_rand(0,$this->height - 15);
imagechar($this->image,8,$x,$y,$this->code[$i],$this->darkColor());
}
}
protected function drawalDisturbe(){
for($i = 0;$i<150;$i++){
$x = mt_rand(0,$this->width);
$y = mt_rand(0,$this->height);
imagesetpixel($this->image,$x,$y,$this->lightColor());
}
}
protected function show(){
header('Content-Type:image/png');
imagepng($this->image);
}
protected function createImage(){
$this->image = imagecreatetruecolor($this->width,$this->height);
}
}
$Code = new Code(4,3);
$Code->outPutImage();