登录的验证码(个人笔记)
登录的验证码
创建一个controller类,写一个生成二维码的方法,启动项目,访问controller的路径
@Controller
@RequestMapping("/captcha")
public class CaptchaController {
//像素宽度
private int width = 130;
//像素高度
private int height = 30;
//验证码文字个数
private int captchaCount = 6;
//文字的间隔
private int space = 16;
//验证码位置
private int drawY = 20;
//验证码的值
private String code[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "X", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
//生成验证码
@RequestMapping("code")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//在内存中绘制一个图片BufferImage,向这个图片写入文字。
//创建一个背景透明的图片,使用rgb表示颜色
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取画笔
Graphics graphics = image.getGraphics();
//把画笔变成百色
graphics.setColor(Color.white);
//给image花板都涂成白色
graphics.fillRect(0, 0, width, height);
//设置字体
Font font = new Font("微软雅黑", Font.BOLD, 16);
graphics.setFont(font);
//设置字体的颜色
graphics.setColor(Color.BLACK);
//测试一个字
//graphics.drawString("超",10,drawY);
int ran = 0;
int len = code.length;
//把验证码保存到buffer中
StringBuffer buffer = new StringBuffer();
//循环获取6个值
for (int i = 0; i < captchaCount; i++) {
ran = new Random().nextInt(len);
//设置字体随机颜色
graphics.setColor(makeColor());
buffer.append(code[ran]);
//字体的位置 字体 X坐标 Y坐标
graphics.drawString(code[ran], (i + 1) * space, drawY);
}
//设置干扰线
for (int i = 0; i < 5; i++) {
int[] dot = makeLineDot();
//前两个参数是起点,后两个是终点
graphics.drawLine(dot[0], dot[1], dot[2], dot[3]);
}
//设置没有缓存
response.setHeader("Prama", "no-cache");
response.setHeader("Cache-Control", "no-cache");
//设置过期时间
response.setDateHeader("Expire", 0);
//把验证码保存到会话中
request.getSession().setAttribute("code", buffer.toString());
//文本格式
response.setContentType("image/png");
//输出流
OutputStream stream = response.getOutputStream();
/**
* RenderedImage im 输出的图片,
* String formatName 图片类型,
* ImageOutputStream output 输出的地方
*/
ImageIO.write(image, "png", stream);
stream.flush();
stream.close();
}
//字体的随机颜色
private Color makeColor() {
Random random = new Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
return new Color(r, g, b);
}
//设置干扰线
private int[] makeLineDot() {
Random random = new Random();
int x1 = random.nextInt(width / 2);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
return new int[]{x1, y1, x2, y2};
}
}