图形验证码的宽高在程序已写死,只需在前端 img 标签设置指定宽高即可。
package com.mvc.controller.base;
import com.mvc.common.Const;
import com.mvc.utils.GenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* SecurityController
*
* @author smallk
* @date 2018/7/29 22:52
*/
@Slf4j
@Controller
public class SecurityController {
/**
* 图形验证码
* graphics.fillRect(x, y, width, height);
* 描述:以图形的左上角为原点,x相当于距离顶部多少,y相当于距离左边多少
*
* @param request HttpServletRequest
* @param response HttpServletResponse
*/
@GetMapping("/valid-code")
public void validCode(HttpServletRequest request, HttpServletResponse response) {
try {
int width = 200;
int height = 100;
int drawLineLen = 10;
Random random = new Random();
// 告知浏览器当作图片处理
response.setContentType("image/jpeg");
// 告知浏览器不缓存
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setHeader("expires", "0");
// 获取四位随机验证码
String validCode = GenerateUtil.getFourCodeNum();
// 把产生的验证码存入到Session中
request.getSession().setAttribute(Const.SESSION_VALID_CODE, validCode);
// 构造一个类型为预定义图像类型之一的 BufferedImage
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取一个Graphics
Graphics graphics = img.getGraphics();
// 将此图形上下文的当前颜色设置为指定颜色
graphics.setColor(Color.WHITE);
// 填充指定的矩形
graphics.fillRect(0, 0, width, height);
// 填充干扰线
for (int i = 0; i < drawLineLen; i++) {
graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
// 在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线
graphics.drawLine(random.nextInt(width + 1), random.nextInt(height + 1), random.nextInt(width + 1), random.nextInt(height + 1));
}
graphics.setColor(Color.BLUE);
// 绘制指定矩形的边框
graphics.drawRect(0, 0, width - 1, height - 1);
// 根据指定名称、样式和磅值大小,创建一个新Font,在组合成Font数组
Font[] fonts = {new Font("隶书", Font.BOLD, 100), new Font("楷体", Font.BOLD, 100), new Font("宋体", Font.ITALIC, 100), new Font("幼圆", Font.ITALIC, 100)};
for (int i = 0; i < validCode.length(); i++) {
graphics.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150)));
// 将此图形上下文的字体设置为指定字体
graphics.setFont(fonts[random.nextInt(fonts.length)]);
// 使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本
graphics.drawString(validCode.charAt(i) + "", 45 * i + 3, 85);
}
// 释放此图形的上下文以及它使用的所有系统资源
graphics.dispose();
// 使用支持给定格式的任意 ImageWriter 将一个图像写入 OutputStream
ImageIO.write(img, "jpeg", response.getOutputStream());
} catch (Exception e) {
log.error("", e);
e.printStackTrace();
}
}
}
网友评论