php+二维码图片生成封装成对象类

6 篇文章 0 订阅
2 篇文章 0 订阅
<?php 
session_start();
//验证码类
/*
 * 背景
 * 干扰
 * 文字
 * 输出
 * 释放资源
 */
class Code{
    public $img; //画布资源
    public $width; //验证码画布的宽
    public $height; //验证码画布的高
    public $length; //验证码的位数
    public $words;  //验证码的文字,
                    //此成员属性用于保存到session中
                    //也用于将此文字输出到画布上

    //构造方法 给成员属性赋初值
    function __construct($width,$height,$length){
        $this->width = $width;
        $this->height = $height;
        $this->length = $length;
    }

    //出口程序
    function printImg(){
        //背景
        $this->bg();
        //干扰
        $this->disturb();
        //产生文字
        $this->getCode();
        //将文字画到画布上
        $this->printWord();    

        //输出
        $this->outImg();
    }
    //背景
    private function bg(){      
        $this->img = imagecreatetruecolor($this->width,$this->height);
        $bg_color = imagecolorallocate($this->img,rand(200,255),rand(200,255),rand(200,255));
        imagefill($this->img,0,0,$bg_color);
    }
    //干扰
    private function disturb(){
        for($i=0;$i<100;$i++){
            //随机输出100个点
            $color = imagecolorallocate($this->img,rand(100,200),rand(100,200),rand(100,200));
            imagesetpixel($this->img,rand(1,$this->width-1),rand(1,$this->height-1),$color);
        }


        for($i=0;$i<10;$i++){
            //随机输出10条线
            $color = imagecolorallocate($this->img,rand(100,200),rand(100,200),rand(100,200));
            imageline($this->img,
                      rand(1,$this->width-1),rand(1,$this->height-1),
                      rand(1,$this->width-1),rand(1,$this->height-1),
                      $color);
        }
    }
    //文字
    //生成验证码文字(4位)
    private function getCode(){
        $cods = "1234567890abcdefghijklmnopqrstuvwxyz";    
        for($i=0;$i<$this->length;$i++){
            //循环随机从codes里取字母
            $this->words.= substr($cods,
                    rand(0,strlen($cods)-1),
                     1);
        }
        $_SESSION['vcode']=$this->words;      
    }
    //将验证码文字在图片上输出
    private function printWord(){
        for($i=0;$i<$this->length;$i++){
            $color = imagecolorallocate($this->img,rand(0,100),rand(0,100),rand(0,100));
            $font = 5;
            $x = ($this->width/$this->length)*$i+5;
            $y = rand(5,10);
            $code = substr($this->words,$i,1);
            imagestring($this->img,$font,$x,$y,$code,$color);
        }
    }


    //输出
    private function outImg(){
        header("Content-Type:image/png");
        imagepng($this->img);
    }

    //释放资源
    function __destruct(){
        imagedestroy($this->img);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值