- /**
- * 通用驗證碼類 img.php
- * 版本:V0.1
- * bbs.it-home.org 2013/3/1
- */
- class ValidateCode {
- private $charset="abcdefghizklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; //隨機因子
- private $code; //驗證碼文字
- private $codelen=4; //驗證碼顯示幾個文字
- private $width=130; //驗證碼寬度
- private $height=50; //驗證碼高度
- private $img; //驗證碼資源控制代碼
- private $font; //指定的字型
- private $fontsize=20; //指定的字型大小
- private $fontcolor; //字型顏色 隨機
- //構造類 編寫字型
- public function __construct(){
- $this->font=ROOT_PATH.'/font/elephant.ttf';
- }
- //建立4個隨機碼
- private function createCode(){
- $_leng=strlen($this->charset);
- for($i=1;$i<=$this->codelen;$i++){
- $this->code.=$this->charset[mt_rand(0,$_leng)];
- }
- return $this->code;
- }
- //建立背景
- private function createBg(){
- //建立畫布 給一個資源jubing
- $this->img=imagecreatetruecolor($this->width,$this->height);
- //背景顏色
- $color=imagecolorallocate($this->img,mt_rand(157,255),mt_rand(157,255),mt_rand(157,255));
- //畫出一個矩形
- imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);
- }
- //建立字型
- private function createFont(){
- $_x=($this->width / $this->codelen); //字型長度
- for ($i=0;$i<$this->codelen;$i++){
- //文字顏色
- $color=imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
- //資源控制代碼 字型大小 傾斜度 字型長度 字型高度 字型顏色 字型 具體文本
- imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height/1.4,$color,$this->font,$this->code[$i]);
- }
- }
- //隨機線條
- private function createLine(){
- //隨機線條
- for ($i=0;$i<6;$i++){
- $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
- imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
- }
- //隨機雪花
- for ($i=0;$i<45;$i++){
- $color = imagecolorallocate($this->img,mt_rand(220,255),mt_rand(220,255),mt_rand(220,255));
- imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
- }
- }
- //輸出背景
- private function outPut(){
- //產生標題
- header('ContentType:img/png');
- //輸出圖片
- imagepng($this->img);
- //銷毀結果集
- imagedestroy($this->img);
- }
- //對外輸出
- public function doimg(){
- //載入背景
- $this->createBg();
- //負載檔案
- $this->createCode();
- //載入線條
- $this->createLine();
- //載入字型
- $this->createFont();
- //載入背景
- $this->outPut();
- }
- //擷取驗證碼
- public function getCode(){
- return strtolower($this->code);
- }
- }
- ?>
複製代碼
調用樣本:index.php 為大家推薦幾篇有關php驗證碼的文章:php隨機驗證碼 php產生隨機驗證碼(圖文)用php產生帶有雪花背景的驗證碼php寫的一個驗證碼php產生動態圖片驗證碼的一段代碼 |