File: /web/data/www.tbbprovision.com/lib/class/img_code.class.php
<?php
basename($_SERVER['PHP_SELF'])==basename(__FILE__) && img_code::create($_GET['name'], (int)$_GET['length'], $_GET['charset']);
class img_code{
private static $cfg=array(
'width' => 37.5, //每个字所占的宽度
'height' => 37, //图片高度
'noise_count' => 10, //杂点数量
'line_count' => 20, //干扰线数量
'ttf' => '../../static/fonts/arial.ttf', //随机验证码使用的字体
'length' => 4, //随机验证码默认长度
'charset' => 'num', //随机验证码默认使用的字符集
'char_table' => array(
'en' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'num' => '0123456789',
'mix' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
)
);
public static function create($name='tbb', $length=4, $charset='en'){
if(basename($_SERVER['PHP_SELF'])==basename(__FILE__)){
self::create_run($name, $length, $charset);
}else{
$img_url="/lib/class/img_code.class.php?name=$name&length=$length&charset=$charset";
return "<img src='$img_url' onclick='this.src=\"$img_url&r=\"+Math.random();' style='cursor:pointer;'>";
}
}
private static function create_run($name, $length, $charset){
$name=='' && exit();
($length<1 || $length>6) && $length=self::$cfg['length'];
!array_key_exists($charset, self::$cfg['char_table']) && $charset=self::$cfg['charset'];
$img_width=$length*self::$cfg['width']; //图片宽度
$img_height=self::$cfg['height']; //图片高度
$image=imagecreate($img_width, $img_height);
//imagecolorallocate($image, 0xff, 0xff, 0xff); //设定背景颜色
imagecolorallocate($image, 255,255,255); //设定背景颜色
// imagerectangle($image, 0, 0, $img_width+1, $img_height+1, imagecolorallocate($image, 0xcc, 0xcc, 0xcc)); //加个边框
for($i=0; $i<self::$cfg['noise_count']; $i++){ //加入杂点
imagesetpixel($image, mt_rand(1, $img_width), mt_rand(1, $img_height), self::rand_color($image));
}
for($i=0; $i<self::$cfg['line_count']; $i++){ //加入干扰线
imageline($image, mt_rand(1, $img_width), mt_rand(1, $img_height), mt_rand(1, $img_width), mt_rand(1, $img_height), self::rand_color($image));
}
$posX=self::$cfg['width']/2-7; //posX,posY代表了首字符的基本点,即第一个字符的左下角
$posY=self::$cfg['width']/2+5;
@session_start();
$_SESSION['Global']['v_code'][md5($name)]='';
for($i=0; $i<$length; $i++){
$code=substr(self::$cfg['char_table'][$charset], mt_rand(0, strlen(self::$cfg['char_table'][$charset])-1), 1);
imagettftext($image, mt_rand(16, 22), mt_rand(-30, 30), $posX, $posY, self::rand_color($image), self::$cfg['ttf'], $code);
//imagettftext($image, 12, 0, $posX, $posY, self::rand_color($image), self::$cfg['ttf'], $code);
$posX+=self::$cfg['width'];
$_SESSION['Global']['v_code'][md5($name)].=$code;
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
}
private static function rand_color($image){
$R=mt_rand(0, 255);
$G=mt_rand(0, 255);
$B=mt_rand(0, 255);
($R>200 && $G>200 && $B>200) && $R=$G=$B=0;
return imagecolorallocate($image, $R,$G,$B );
}
}
?>