生成验证码工具类:
package com.qxs.utils;
import java.util.Random;
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CodeUtils {
private static int width = 220;// 验证码宽度
private static int height = 70;// 验证码高度
private static Random random = new Random();
public static void getCode(HttpServletRequest request, HttpServletResponse response, int len) throws IOException {
// 创建一张空白图片,宽度,高度,图片类型
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取到画笔
Graphics g = image.getGraphics();
// 给画笔设置颜色
g.setColor(randomColor());
// 使用画笔填充一个矩形
g.fillRect(0,0, width, height);
// 得到随机验证码
String code = randomCode(len);
// 把验证码存入session
request.getSession().setAttribute("vcode", code);
g.setFont(new Font(null,Font.BOLD+Font.ITALIC, height/2));
// 把验证码画到图画上。
for (int i = 0; i < code.length() ; i++) {
char c = code.charAt(i);// 取出一个字符
// 给画笔设置一个颜色
g.setColor(randomColor());
// 在图片上面写字
int w = width / (len + 1);
g.drawString(c+"",w + i*w - (w/2), 45);
}
// 画干扰线
for (int i = 0; i < 5; i++) {
g.setColor(randomColor());
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
// 画干扰雪花
for (int i = 0; i < 5; i++) {
g.setColor(randomColor());
int x = random.nextInt(width+1);
int y = random.nextInt(height+1);
g.drawString("*", x, y);
}
ImageIO.write(image,"png", response.getOutputStream());
}
// 随机获取一个颜色
private static Color randomColor() {
int r = random.nextInt(256),
g = random.nextInt(256),
b = random.nextInt(256);
return new Color(r, g, b);
}
// 获取随机的验证码
public static String randomCode(int len){
StringBuilder sb = new StringBuilder();
char[] arr = "0123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".toCharArray();
//随机产生四位索引值,然后分别取出字符
for (int i = 0; i < len; i++) {
int index = random.nextInt(arr.length);
sb.append(arr[index]);
}
return sb.toString();
}
}



