运用php GD库的图像函数制作登录验证码图片

<?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();
?>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值