昨天碰到一个需要自己写图片验证码的需要,我用的 Lumen 框架中没有这个功能,需要自己写,网上搜了下,记录成一篇笔记.
代码
- <
* / \
* // \\
* //| . |\\
* "'\ /'"_.-~^`'-.
* \ _ /--' `
* ___)( )(___
* (((__) (__))) 高山仰止,景行行止.虽不能至,心向往之.
*
*/
namespace App\Tools;
class VerifyCodeImage {
private $width;
private $height;
private $str;
private $im;
private $strColor;
function __construct($width, $height,$image_code) {
$this->width = $width;
$this->height = $height;
$this->str = $image_code;
$this->createImage();
}
/**
* 生成图片二维码
*/
function createImage() {
$this->im = imagecreate($this->width, $this->height);//创建画布
imagecolorallocate($this->im, 200, 200, 200);//为画布添加颜色
for ($i = 0; $i < strlen($this->str); $i++) {//循环输出四个数字
$this->strColor = imagecolorallocate($this->im, rand(0, 100), rand(0, 100), rand(0, 100));
imagestring($this->im, rand(3, 5), $this->width / 4 * $i + rand(5, 10), rand(2, 5), $this->str[$i], $this->strColor);
}
for ($i = 0; $i < 100; $i++) {//循环输出200个像素点
$this->strColor = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($this->im, rand(0, $this->width), rand(0, $this->height), $this->strColor);
}
}
/**
* 生成图片二维码并保存
* @return string
*/
function show($openid) {
try{
removeDir("./imgcode");
$path = "./imgcode/".date("Y-m-d",time())."/".$openid."/";
if (!is_dir($path)){ //判断目录是否存在 不存在就创建
mkdir($path,0777,true);
}
$filename = $path.time().'.png'; //设置文件名
header('content-type:image/png');//定义输出为图像类型
imagepng($this->im,$filename);//生成图像
imagedestroy($this->im);//销毁图像释放内存
return $filename;
}catch (\Exception $exception){
operate_log("0","生成图片二维码失败",$exception);
return false;
}
}
}
使用如下:
use App\Tools\VerifyCodeImage;
$router->get('/', function () use ($router) {
$imageCode = new VerifyCodeImage(80,20,'5698');
$file_path = $imageCode->show('123456789');
return [
"file_path" => env("CSV_HOST").ltrim($file_path,"./")
];
});
如果是直接输出图片,可以把 show() 方法改成
function show() {
header('content-type:image/png');//定义输出为图像类型
imagepng($this->im);//生成图像
imagedestroy($this->im);//销毁图像释放内存
}