新代码
/**
* 获取验证码和图片
*
* @return list包含两个对象,第一个是验证码对应字符串(String),第二个是验证码图片(BufferedImage)
*/
public static ArrayList<Object> getSecurityCode() {
StringBuilder sb = new StringBuilder();
int width = 120;
int height = 40;
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Random ran = new Random();
BufferedImage bufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bufImage.getGraphics();
g.setColor(new Color(ran.nextInt(50), ran.nextInt(50), ran.nextInt(50)));
g.fillRect(0, 0, width, height);
g.setFont(new Font("font", Font.BOLD, 30));
for (int i = 1; i <= 4; i++) {
g.setColor(new Color(ran.nextInt(55) + 200, ran.nextInt(55) + 200, ran.nextInt(55) + 200));
char ch = chars[(int) (Math.random() * chars.length)];
sb.append(ch);
int jiaodu = (int) (Math.random() * 60) - 30;
double theta = jiaodu * Math.PI / 180;
g.rotate(theta, width / 5 * i, height - 10);
g.drawString(ch + "", width / 5 * i - 8, height - 10);
g.rotate(-theta, width / 5 * i, height - 10);
}
int x1, x2, y1, y2;
for (int i = 0; i < 5; i++) {
g.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
x1 = (int) (Math.random() * width);
x2 = (int) (Math.random() * width);
y1 = (int) (Math.random() * height);
y2 = (int) (Math.random() * height);
g.drawLine(x1, y1, x2, y2);
}
g.dispose();
ArrayList<Object> list = new ArrayList<>();
list.add(sb.toString());
list.add(bufImage);
return list;
}
servlet配置
// 设置不缓存图片
response.setHeader("Pragma", "No-cache")
response.setHeader("Cache-Control", "No-cache")
response.setDateHeader("Expires", 0)
// 设置响应图片类型
response.setContentType("image/jpeg")
// 输出图片
ImageIO.write(image,"JPEG",response.getOutputStream())
生成验证码示例
修改
- 修改了背景和字体颜色取值范围,背景深色,字体浅色,解决验证码字体可能看不清的问题
- 字体整体向左移动8个单位以居中
修改后生成的验证码