GD 验证码类

来源:互联网 发布:电机软件控制工程师 编辑:程序博客网 时间:2024/06/05 08:00
<?php /* * 1、创建画布 * 2、干扰 * 3、文字 * 4、输出 * 5、释放资源*/class Code{    public $img;    public $width; //验证码的宽    public $height; //验证码的高    public $length; //验证码的长度(位数)    public $word;   //验证码文字 - session 输出图片    //给成员属性赋初值    function __construct($width,$height,$length){        $this->width = $width;        $this->height = $height;        $this->length = $length;        //在类被实例化时,调用成员方法getWord        //获取验证码的文字              $this->word = $this->getWord();    }    //定有出口程序    function printImage(){        $this->bg();        $this->disturb();        $this->outWord();        $this->outImage();    }    //1、创建画布(背景色浅色 颜色随机)    private function bg(){          $this->img = imagecreatetruecolor($this->width,$this->height);        //画布的背景色        $bgColor = imagecolorallocate($this->img, rand(200,255), rand(200,255), rand(200,255));        //填充背景色        imagefill($this->img,0,0,$bgColor);            }    // * 2、干扰    private function disturb(){        //100个随机出现的点        for($i=0;$i<100;$i++){            $color = imagecolorallocate($this->img,                    rand(100,200),                    rand(100,200),                    rand(100,200));            imagesetpixel($this->img,rand(1,79),                          rand(1,29),$color);                   }        //10条随机出现的线        for($i=0;$i<10;$i++){            $color = imagecolorallocate($this->img,                    rand(100,200),                    rand(100,200),                    rand(100,200));            imageline($this->img,rand(1,79),rand(1,29)                      ,rand(1,79),rand(1,29),$color);        }    }    //获取文字    function getWord(){        $codes = "0123456789abcdefghijklmnopqrstuvwxyz";        $words = "";        for($i=0;$i<$this->length;$i++){            //循环截取验证码文字            $words.=substr($codes,rand(0,strlen($codes)-1),1);                   }        return $words;    }    //输出验证码图片    //* 3、文字    function outWord(){             for($i=0;$i<$this->length;$i++){            $font = 5;            $x = ($this->width/$this->length)*$i+5;            $y = rand(5,10);            $code = substr($this->word,$i,1);            $color = imagecolorallocate($this->img,                    rand(0,100), rand(0,100), rand(0,100));            imagestring($this->img,$font,$x,$y,$code,$color);        }    }    //* 4、输出    private function outImage(){        //通知浏览器输出图片        header("Content-Type:image/png");        //GD库函数输出图片        imagepng($this->img);    }    // * 5、释放资源    function __destruct(){        imagedestroy($this->img);    }}
0 0