<?php
/*
* [验证码类]
* @author: luochen[1102564499@qq.com]
* @Date: 2014-04-27 21:06:49
* @Last Modified time: 2014-04-28 20:02:03
*/
class Code{
//验证码显示宽度
private $width;
//验证码显示高度
private $height;
//验证码字体大小
private $fontSize;
//验证码字体文件
private $fontFile;
//验证码字体颜色
private $fontColor;
//验证码背景颜色
private $bgColor;
//验证码长度
private $codeLen;
//验证码种子
private $seek;
//资源
private $img;
/**
* [__construct 初始化配置]
* @param [type] $width [description]
* @param [type] $height [description]
* @param [type] $fontSize [description]
* @param [type] $codeLen [description]
* @param [type] $fontFile [description]
* @param [type] $fontColor [description]
* @param [type] $bgColor [description]
*/
public function __construct($width = NULL,$height = NULL,$fontSize = NULL, $codeLen = NULL,$fontFile = NULL, $fontColor = NULL, $bgColor = NULL){
$this->width = is_null($width) ? 200 : $width;
$this->height = is_null($height) ? 50 : $height;
$this->fontSize = is_null($fontSize) ? 24 : $fontSize;
$this->codeLen = is_null($codeLen) ? 4 : $codeLen;
$this->fontFile = is_null($fontFile) ? './font.ttf' : $fontFile;
$this->fontColor = is_null($fontColor) ? '#000000' : $fontColor;
$this->bgColor = is_null($bgColor) ? '#ffffff' : $bgColor;
$this->seek = 'qwertyuiopasdfghjklzxcvbnm1234567890';
}
/**
* [show 显示验证码]
* @return [type] [description]
*/
public function show(){
//发送头部
header('Content-type:image/png');
//创建背景
$this->_create_bg();
//画点
$this->_create_point();
//画线
$this->_create_line();
//写字
$this->_create_font();
//输出
imagepng($this->img);
//销毁资源
imagedestroy($this->img);
}
/**
* [_create_font 写字]
* @return [type] [description]
*/
private function _create_font(){
$str = '';
for ($i=0; $i < $this->codeLen; $i++) {
//x
$x = $this->width / $this->codeLen;
$x = $x * $i + 15;
//y
$y = ($this->height + $this->fontSize) / 2;
//转换字体颜色
$fontColor = hexdec($this->fontColor);
//随机字
$seek = $this->seek;
$text = $seek[mt_rand(0,strlen($seek) - 1)];
imagettftext($this->img, $this->fontSize, mt_rand(-45,45), $x, $y, $fontColor, $this->fontFile, $text);
$str .= $text;
}
//保存到session?
}
/**
* [_create_line 干扰线]
* @return [type] [description]
*/
private function _create_line(){
for ($i=0; $i < 10; $i++) {
$color = imagecolorallocate($this->img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imageline($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
}
}
/**
* [_create_point 干扰点]
* @return [type] [description]
*/
private function _create_point(){
for ($i=0; $i < 200; $i++) {
$color = imagecolorallocate($this->img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagesetpixel($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
}
}
/**
* [_create_bg 创建背景]
* @return [type] [description]
*/
private function _create_bg(){
//创建画布
$img = imagecreatetruecolor($this->width, $this->height);
//创建背景色
$bgColor = hexdec($this->bgColor);
//填充
imagefill($img, 0, 0, $bgColor);
//保存到类的属性里面
$this->img = $img;
}
}