<?php
class testcode{
private $imageRes;
private $bgColor;
private $textColor;
private $width;
private $height;
private $codeNum;
/**
* 构造函数
*/
public function __construct($width = 150,$height = 30,$codeNum = 4){
$this->imageRes = $this->initImg();
$this->width = $width;
$this->height = $height;
$this->codeNum = $codeNum;
$this->textColor = imagecolorallocate($this->imageRes,0,255,127);
$this->bgColor = imagecolorallocate($this->imageRes,0,0,0);
}
/**
* 画布初始化
*/
public function initImg(){
return imagecreatetruecolor(200,200);
}
/**
* 生成验证码
*/
public function codeCreate(){
return strtoupper(substr(md5(rand()),0,$this->codeNum));
}
/**
* 背景颜色设置
*/
public function setBgColor(){
imagefill($this->imageRes,0,0,$this->bgColor);
}
/**
* 画点
*/
public function pixelCreate(){
for($i=0;$i<20000;$i++){
imagesetpixel($this->imageRes,mt_rand(1,300),mt_rand(1,300),$this->textColor);
}
}
/**
* 画线
*/
public function lineCreate(){
for($i=0;$i<20;$i++){
imageline($this->imageRes,mt_rand(0,140),mt_rand(0,200),mt_rand(0,140),mt_rand(0,200),$this->textColor);
}
}
/**
* 将验证码写进画布
*/
public function drawCode($code){
$filePath = 'simsun.ttc';
imagettftext($this->imageRes,65,5,15,120,$this->textColor,$filePath,$code);
}
/**
* 生成验证码、保存验证码和验证码图片
*/
public function code(){
$code = $this->codeCreate();//生成验证码
file_put_contents("./codeRecord.txt", $code);//保存验证码
$this->drawCode($code);//将验证码写入画布
$this->setBgColor();//设置背景颜色
$this->pixelCreate();//画点
$this->lineCreate();//画线
header("Content-type:image/jpeg");
imagejpeg($this->imageRes,'./imagecode/code.jpg');//保存图片
imagejpeg($this->imageRes);
}
}
$newCodeImg = new testcode();
$newCodeImg->code();
?>
运用php GD库的图像函数制作登录验证码图片
最新推荐文章于 2018-06-03 23:49:32 发布