最简单的单文件php写一个验证码的类

最简单的单文件php写一个验证码的类_第1张图片



namespace support;

class Captcha
{
    private $width;
    private $height;
    private $length;
    private $font;
    private $code;

    public function __construct($width = 120, $height = 40, $length = 4, $font = 'arial.ttf', $fontSize = 20, $bgColor = '#FFFFFF', $textColor = '#000000')
    {
        $this->width = $width;
        $this->height = $height;
        $this->length = $length;
        $this->font = $font;
        $this->fontSize = $fontSize;
        $this->bgColor = $bgColor;
        $this->textColor = $textColor;
        $this->code = $this->generateCode();
    }

    private function generateCode()
    {
        $code = '';
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $this->length; $i++) {
            $code .= $chars[random_int(0, $max)];
        }
        return $code;
    }

    public function getCode()
    {
        return $this->code;
    }

    public function generateImage()
    {
        $image = imagecreatetruecolor($this->width, $this->height);
        $bgColor = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $bgColor);
        $fontPath = __DIR__ . '/' . $this->font;
        for ($i = 0; $i < $this->length; $i++) {
            // 控制字体颜色
            $textColor = imagecolorallocate($image, random_int(0, 100), random_int(0, 100), random_int(0, 100));
            $fontSize = random_int(18, 20);
            $angle = random_int(-25, 25);
            $x = ($this->width / $this->length) * $i + random_int(5, 10);
            $y = random_int($this->height / 2, $this->height - 10);
            $char = $this->code[$i];
            imagettftext($image, $fontSize, $angle, $x, $y, $textColor, $fontPath, $char);
            imageline($image, random_int(0, $this->width), random_int(0, $this->height), random_int(0, $this->width), random_int(0, $this->height), $textColor);
            imagearc($image, random_int(0, $this->width), random_int(0, $this->height), random_int(0, $this->width), random_int(0, $this->height), random_int(0, 360), random_int(0, 360), $textColor);
        }
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);
    }
}

调用方法:

    /**
     * 输出验证码图像
     */
    public function captcha(Request $request)
    {
        // 初始化验证码类
        $builder = new Captcha();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getCode()));
        // 获得验证码图片二进制数据
        ob_start();
        $builder->generateImage();
        $img_content = ob_get_clean();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/png']);
    }

你可能感兴趣的:(php,开发语言)