用户
 找回密码
 入住 CI 中国社区
搜索
查看: 1726|回复: 2
收起左侧

[讨论/交流] 自定义类库,验证码无法生成

[复制链接]
发表于 2016-3-7 19:52:44 | 显示全部楼层 |阅读模式
不用CI框架原来的验证码,采用自定义的验证码类库,放在 application/libraries/Code.php,这个类的代码为:
PHP复制代码
class Code{
    private $w = 0; //宽
    private $h = 0; //高
    private $str = 'qwertyuipkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM23456789';
    private $code = '';
 
    public function __construct(){
        $this->set();
        $this->random();
    }
 
    //设置验证码图片的长、宽
    public function set($x=60,$y=32){
        $this->w = $x;
        $this->h = $y;
    }
 
    //获取验证码
    public function getCode(){
        return $this->code;
    }
 
       
    //生成验证码图片 png格式
    public function img(){
        $img = imagecreatetruecolor($this->w, $this->h);
 
        $bgcolor = imagecolorallocate($img, 255, 255, 255); //底色
        $txtcolor = imagecolorallocate($img, mt_rand(100, 150), mt_rand(100, 150), mt_rand(100, 150)); //验证码颜色
 
        imagefill($img, 0, 0, $bgcolor); //填充底色
 
        //画线条
        for ($i=0; $i<3; $i++){
            //线条颜色
            $color1 = imagecolorallocate($img, mt_rand(150, 200), mt_rand(150, 200), mt_rand(150, 200));
            imageline($img, 0, mt_rand(0, $this->h), $this->w, mt_rand(0, $this->h), $color1);
        }
 
        //画验证码
        imagestring($img, 5, $this->w/5, $this->h/5, $this->code, $txtcolor);
 
 
 
        //输出图像
        header('Content-type: image/png');
        imagepng($img);
        imagedestroy($img);
    }
 
    //产生4位随机验证码
    protected function random(){
        $arr = str_split($this->str);
        shuffle($arr);
        $tmp = implode('', $arr);
        $this->code = substr($tmp, 0,4);
    }
}
复制代码

然后,楼主对其进行调用,代码为:
PHP复制代码
public function code(){
                $this->load->library('code');
                $this->code->img();
                //var_dump($this->code);
        }
复制代码

结果浏览器,出现的是:只有20X20白点,并没有图片生成,而楼主我用code.php类库,在测试(非CI框架),却可以生成验证码图片,跪求大神来解惑....

 楼主| 发表于 2016-3-7 19:54:41 | 显示全部楼层
调用getCode()方法,可以得到验证码,而生成图片却失败
发表于 2016-3-7 21:27:09 | 显示全部楼层
QQ图片20160307212304.png

Code类要放在application\libraries 下。




本版积分规则