<?php namespace App\Distributor\Controllers; use Dcat\Admin\Http\Controllers\AdminController; use Illuminate\Support\Facades\Session; class CaptchaController extends AdminController { public function generate() { // 生成验证码字符串 $characters = '23456789'; $captchaString = ''; for ($i = 0; $i < 6; $i++) { $captchaString .= $characters[rand(0, strlen($characters) - 1)]; } // 创建图片 $width = 120; $height = 40; $image = imagecreate($width, $height); // 定义颜色 $backgroundColor = imagecolorallocate($image, 243, 243, 243); // 背景色(浅灰色) $textColor = imagecolorallocate($image, 51, 51, 51); // 文本颜色(深灰色) $lineColor = imagecolorallocate($image, 204, 204, 204); // 干扰线颜色(浅灰色) // 添加干扰线(每条线的颜色随机) for ($i = 0; $i < 5; $i++) { $lineColor = imagecolorallocate( $image, rand(0, 255), // 随机红色分量 rand(0, 255), // 随机绿色分量 rand(0, 255) // 随机蓝色分量 ); imageline( $image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor ); } // 添加验证码文本 $fontSize = 5; // 字体大小,GD 内置字体大小范围是 1 到 5 $xOffset = 10; // 起始 X 偏移 for ($i = 0; $i < strlen($captchaString); $i++) { $textColor = imagecolorallocate( $image, rand(0, 150), // 随机红色分量 rand(0, 150), // 随机绿色分量 rand(0, 150) // 随机蓝色分量 ); // 随机调整每个字符的位置 $x = $xOffset + ($i * 15) + rand(-2, 2); // 每个字符的水平位置随机微调 $y = rand(10, $height - imagefontheight($fontSize)); // 垂直位置随机 imagestring( $image, $fontSize, $x, $y, $captchaString[$i], $textColor ); } // 存储验证码文本到会话 Session::put('captcha', $captchaString); // 输出图片 ob_start(); imagepng($image); $imageData = ob_get_clean(); // 释放内存 imagedestroy($image); return response($imageData)->header('Content-Type', 'image/png'); } }