闲着没事干写着玩的、wamp下测试没问题。服务器没有测试,使用请自行测试。代码如下
<?php /** * 验证码生成类 * date 2014年7月26日 星期六 */ session_start(); class generateCode { private $codeLength = 5;//验证码长度 private $height = 70; //画布高度 private $width = 25; //画布宽度 private $fontSize = 10; private $noisenum=100;//干扰点数量 private $code = null; /** * @param int $width 图片宽度 * @param int $height图片高度 * @param int $fontSize 字体大小 * @param int $codeLength 验证码长度 */ public function __construct($width,$height,$fontSize,$codeLength){ $this->width = $width; //图像宽度 $this->height = $height; $this->fontSize = $fontSize; $this->codeLength=$codeLength; $this->code = $this->getCode(); $_SESSION['code'] = $this->code; } public function generate(){ $font = 'Weston.otf'; $img = imagecreate($this->width,$this->height); $black = ImageColorAllocate($img, 0,0,0); //RGB黑色标识符 $white = ImageColorAllocate($img, 255,255,255); //RGB白色标识符 $gray = ImageColorAllocate($img, 200,200,200); //RGB灰色标识符 imagettftext($img, $this->fontSize, 0, 10, 20, $gray, $font, $this->code); //干扰线 $this->setnoise($img,$this->width,$this->height,$this->noisenum); header ( 'Content-type: image/png' ); imagepng($img); imagedestroy($img); } /** * 随机生成验证码字符 * @param int $codeLength //生成随机字符长度 * return $key 返回生成随机字符 */ protected function getCode(){ $codeStr = '23456789ABCDEFGHIJKLOMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';//字符池 $strLeng = strlen($codeStr); for($i=0;$i<$this->codeLength;$i++){ $key.=$codeStr{mt_rand(1,$strLeng)}; } return $key; } /** * 添加干扰点 * @param object $image 图片对象 * @param int $width 图片宽度 * @param int $height 图片高度 * $noisenum 生成点数量 */ protected function setnoise($image,$width,$height,$noisenum){ for ($i=0; $i<$noisenum; $i++){ //分配颜色 $randColor = imageColorAllocate($image, rand(0, 255), rand(0, 255), rand(0, 255)); //画点 imageSetPixel($image, rand(0, $width), rand(0, $height), $randColor); //画线 if($i<3) imageline($image,rand(0, $width),rand(0, $height),rand(0, $width),rand(0, $height),$randColor); } } } $code = new generateCode(100,30,15,5); $code->generate();
使用了一款字体、需要下载字体
点击下载字体
转载注明转自 松林's blog http://www.songlin51.com/archives/1113.html
感觉好专业的代码呀
涨姿势,谢谢分享