手写一个获取验证码的接口,超级简单

手写一个获取验证码的接口,超级简单,觉得有用就试试吧,话不多说代码附上

	private static final int VERIFY_CODE_HEIGHT = 25; //验证码高度
	private static final int VERIFY_CODE_WIDTH = 70; //验证码宽度
	
	private static final char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	/**
	 * 获取验证码
	 * @param req 请求
	 * @param res 响应
	 * @throws IOException
	 */
	@GetMapping("verificationCode")
	public void verificationCode(HttpServletRequest req, HttpServletResponse res) throws IOException {
		BufferedImage image = new BufferedImage(VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT,BufferedImage.TYPE_INT_RGB);
		//获取图片上下文
		Graphics graphics = image.getGraphics();
		//生成随机类
		Random random = new Random();
		//设置背景色
		graphics.setColor(getRandColor(200, 250));
		graphics.fillRect(0, 0, VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT);
		// 设定字体
		graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
		graphics.setColor(getRandColor(160, 200));
		for (int i = 0; i < 160; i++) {
			int x = random.nextInt(VERIFY_CODE_WIDTH);
			int y = random.nextInt(VERIFY_CODE_HEIGHT);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			graphics.drawLine(x, y, x + xl, y + yl);
		}
		// 取随机产生的认证码(4位数字)
		String sRand = "";
		for (int i = 0; i < 4; i++) {	
			String rand = String.valueOf(codeSequence[random.nextInt(10)]);   
			sRand += rand;
			// 将认证码显示到图象中
			graphics.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
			graphics.drawString(rand, 13 * i + 10, 20);
		}
		// 图象生效
		graphics.dispose();
		// 输出图象到页面
		//将VerifyCode绑定session(VerifyCode 可根据实际情况自行定义)
		req.getSession().setAttribute("VerifyCode", sRand);
        //设置响应头
		res.setHeader("Pragma", "no-cache");
        //设置响应头
		res.setHeader("Cache-Control", "no-cache");
        //在代理服务器端防止缓冲
		res.setDateHeader("Expires", 0);
        //设置响应内容类型
		res.setContentType("image/jpeg");   
        ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", out);      
		res.setContentLength(out.size());
		res.getOutputStream().write(out.toByteArray());
		res.getOutputStream().flush();
	}
	

设置背景色

/**
	 * 设置背景色
	 * @param i
	 * @param j
	 * @return
	 */
	private static Color getRandColor(int i, int j) {
		Random random = new Random();
		if (i > 255)
			i = 255;
		if (j > 255)
			j = 255;
		int r = i + random.nextInt(j - i);
		int g = i + random.nextInt(j - i);
		int b = i + random.nextInt(j - i);
		return new Color(r, g, b);
	}
	

Postman请求返回示例

在这里插入图片描述

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小甘说码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值