<?php
/**
* 验证码生成类
* User: xiaoyu
* Date: 2019/4/12
* Time: 11:50
*/
class CaptchaC
{
private $image;
public function __construct()
{
//创建一张底图
$this->image = imagecreatetruecolor(200, 50);
//为一幅图像分配颜色
$bgcolor = imagecolorallocate($this->image, 255, 255, 255);
//区域填充 imagefill() 在 image 图像的坐标 x,y(图像左上角为 0, 0)处用 color
//颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。
imagefill($this->image, 0, 0, $bgcolor);
// $this->alpNum();
$this->cha();
$this->interfere();
}
public function __destruct()
{
imagedestroy($this->image);
}
public function outPut()
{
header('Content-Type: image/png');//加这一句
imagepng($this->image);
}
//生成汉字验证码
public function cha()
{
$fontfile = "MSYH.TTF";//字体样式
$fonts = $this->font();//验证码字体库--
$strdb = str_split($fonts, 3);//中文一个字符占3个字节
$captch_code = '';
for ($i = 0; $i < 4; $i++) {
//为一幅图像分配颜色--随机生成验证码的颜色
$fontcolor = imagecolorallocate($this->image, rand(0, 120), rand(0, 120), rand(0, 120));
$text = $strdb[mt_rand(0, count($strdb) - 1)];
$captch_code .= $text;
//为图像插入字符
imagettftext($this->image, mt_rand(20, 24), mt_rand(-60, 60), (40 * $i + 20), mt_rand(30, 35), $fontcolor, $fontfile, $text);
}
}
//生成字母数字验证码
public function alpNum()
{
session_start();
$content = "ABCDEFGHIJKLMNPQRSTUVWXYabcdefghigkmnpqrstuvwxy3456789";
$captcha = '';
for ($i = 0; $i < 4; $i++) {
$fontsize = 6;
//为一幅图像分配颜色--随机生成验证码的颜色
$fontcolor = imagecolorallocate($this->image, rand(0, 120), rand(0, 120), rand(0, 120));
//substr根据下标截取字符串,strlen获取字符串长度
$fontcontent = substr($content, mt_rand(0, strlen($content) - 1), 1);
$captcha .= $fontcontent;
$x = ($i * 200 / 4) + rand(30, 40);
$y = rand(20, 30);
// 水平地画一行字符串 参数:要画的图像,字体大小,图像的坐标x,y,字体颜色
imagestring($this->image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
$_SESSION['captcha'] = $captcha;
}
//生成干扰元素
public function interfere()
{
for ($i = 0; $i < 300; $i++) {
//为一幅图像分配颜色--随机生成点的颜色
$pointcolor = imagecolorallocate($this->image, rand(50, 200), rand(50, 200), rand(50, 200));
//— 画一个单一像素
imagesetpixel($this->image, rand(1, 199), rand(1, 59), $pointcolor);
}
for ($i = 0; $i < 3; $i++) {
//为一幅图像分配颜色--随机生成线的颜色
$linecolor = imagecolorallocate($this->image, rand(80, 220), rand(80, 220), rand(80, 220));
//— 画一条线段 需要俩个点确定一条线
imageline($this->image, rand(1, 199), rand(1, 59), rand(1, 199), rand(1, 59), $linecolor);
}
}
//验证码字体库--
private function font()
{
return "关雎鸠在河洲窈窕淑君子好逑参差荇菜左流窈窕淑女寤寐求求不得寤寐思服悠哉悠哉辗转反侧参差荇菜右采之窈窕淑琴瑟友参差荇菜左右芼窈窕钟鼓乐蒹葭苍苍白露为霜所谓伊人在水一方溯洄从之道阻且长溯游从之宛在水中央蒹葭凄凄白露未晞所谓伊人在水之湄溯洄从之道阻且跻溯游从之宛在水中坻蒹葭采采白露未已所谓伊人在水之涘溯洄从之道阻且右溯游从之宛在水中沚";
}
}
打开App,阅读手记