您的位置:首页 > 编程语言 > PHP开发

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

2017-01-16 22:56 190 查看
<?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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  验证码 php session class