设计类
{
属性:
宽度 int $width
高度 int $hight
干扰点
验证码(私有的)
验证码字符的个数 int $number
验证码的类型(纯数字类型、纯字母类型、混合类型)
背景颜色 string $color
字体颜色 string $fontColor
图片类型(jpg、png、bmp……) string $imageType
图片资源 string $resource
功能:
构造函数(用来初始化) function
生成验证码的函数 function createCode
创建画布 function createImage
填充背景色 function fillBackground
填充干扰点
填充干扰弧线
画验证码
输出图片
}
实现
<?php
Class Code{
public $width;
public $height;
public $numbers;
public $codeType;
public $color;
public $fontColor;
public $imageType;
private $codeString;
private $resource;
public function __construct($w=100,$h=50,$n=4,$imageType='png',$codeType=1){
$this->width = $w;
$this->height = $h;
$this->numbers = $n;
$this->imageType = $imageType;
$this->codeType = $codeType;
$this->codeString = $this->createCode($this->codeType);
$this->show();
}
private function createCode($type){
switch($type){
case 1:
$this->codeString = join('',array_rand(range(0, 9),$this->numbers));
break;
case 2:
$this->codeString = implode(array_rand(array_filp(array_merge(range('a','z'),range('A','Z'))),$this->numbers));
case 3:
$words = str_shuffle('abcdefghjkmpopqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXY3456789');
$this->codeString = substr($words,0,$this->numbers);
break;
}
return $this->codeString;
}
private function show(){
$this->createImg();
$this->fillBackground();
$this->fillPix();
$this->fillArc();
$this->writeFont();
$this->outPutImg();
}
private function createImg(){
$this->resource = imagecreatetruecolor($this->width,$this->height);
}
private function setDarkColor()
{
return imagecolorallocate($this->resource,mt_rand(130,255),mt_rand(130,255),mt_rand(130,255));
}
private function setLightColor()
{
return imagecolorallocate($this->resource,mt_rand(0,130),mt_rand(0,130),mt_rand(0,130));
}
private function fillBackground()
{
imagefill($this->resource,0,0,$this->setDarkColor());
}
private function fillPix()
{
$num = ceil(($this->width * $this->height) / 20);
for($i = 0; $i < $num; $i++){
imagesetpixel($this->resource,mt_rand(0,$this->width),mt_rand(0,$this->height),$this->setDarkColor());
}
}
private function fillArc()
{
for($i = 0;$i < 10;$i++){
imagearc($this->resource,
mt_rand(10,$this->width-10),
mt_rand(5,$this->height-5),
mt_rand(0,$this->width),
mt_rand(0,$this->height),
mt_rand(0,180),
mt_rand(181,360),
$this->setDarkColor());
}
}
private function writeFont()
{
$every = ceil($this->width / $this->numbers);
for($i = 0;$i < $this->numbers;$i++){
$x = mt_rand(($every * $i) + 5,$every * ($i + 1) - 5);
$y = mt_rand(5,$this->height - 10);
imagechar($this->resource,6,$x,$y,$this->codeString[$i],$this->setLightColor());
}
}
private function outPutImg()
{
header('Content-type:image/'.$this->imageType);
$func = 'image'.$this->imageType;
$func($this->resource);
}
public function __get($name){
if($name = 'codeString'){
return $this->codeString;
}
}
public function __destruct()
{
imagedestroy($this->resource);
}
}