package com.htc.utils;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@Component
public class CodeUtils {
public void code(HttpSession session, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
//设置页面不能缓存
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","No-cache");
response.setDateHeader("Expires", 0);
int width=60,height=30;
// 绘制带缓冲区的图片
BufferedImage pic = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics gc = pic.getGraphics();
gc.setColor(getRandomColor(200,255)); //设置画布的背景 颜色
gc.fillRect(0,0,width,height);//填充矩形
gc.setFont(new Font("宋体",Font.PLAIN,20));
//设置干扰线
Random r = new Random();
for (int i = 0; i <300 ; i++) {
int x1= r.nextInt(width);
int y1= r.nextInt(height);
int x2= r.nextInt(15);
int y2= r.nextInt(15);
gc.setColor(getRandomColor(160,200)); //设置画布的背景 颜色
gc.drawLine(x1,y1,x2,y2);
}
//设置干扰点
for (int i = 0; i <150 ; i++) {
int x1= r.nextInt(width);
int y1= r.nextInt(height);
gc.setColor(getRandomColor(100,160)); //设置画布的背景 颜色
gc.drawOval(x1,y1,0,0);
}
//生成验证码
String RS= r.nextInt(9000)+1000+"";
gc.setColor(getRandomColor(0,100)); //设置字体的背景 颜色
gc.drawString(RS,10,16);
gc.dispose();
//你需要判断用户输入的验证码和你产生的验证码是否一致
session.setAttribute("random",RS);
ImageIO.write(pic,"JPEG",response.getOutputStream());
}
public Color getRandomColor(int min,int max){
// 0 -- 255
Random radom = new Random();
if(min>255){
min=255;
}
if(max>255){
max=255;
}
int r = radom.nextInt(max-min)+min;
int g = radom.nextInt(max-min)+min;
int b = radom.nextInt(max-min)+min;
return new Color(r,g,b);
}
}
生成验证码的工具类
于 2023-07-14 14:34:18 首次发布