写好一份获取验证码逻辑, 记录已做备用
// 1.定义一个随机字典
public static final char[] chars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };
//2 定义生成随机数
private static Random random = new Random();
//获取随机六位数
public static String getRandomString(){
//字符串缓冲 ,进行拼接
StringBuffer sb = new StringBuffer();
for(int i = 0;i <4;i++){
//每次获取一个随机字符串
sb.append(chars[random.nextInt(chars.length)]);
}
return sb.toString();
}
//获取一个颜色 分别用于前景色(文字的颜色)和背景色
public static Color getRandomColor(){
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
//获取随机颜色的反色
public static Color getReverColor(Color c){
return new Color(255-c.getRed(), 255-c.getGreen(), 255-c.getBlue());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//随机字符串
String randomString = getRandomString();
//随机颜色 背景色
Color c =getRandomColor();
//反色 用于前景色
Color reverse =getReverColor(c);
//创建一个彩色的图片 根据BufferedImage(长度,宽度,生成的类型)
BufferedImage bi =new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
//获取绘图对象,画笔
Graphics g = bi.getGraphics();
//设置字体
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,20));
//设置字体的颜色
g.setColor(c);
//绘制背景
g.fillRect(0, 0, 100, 30);
//设置前景色
g.setColor(reverse);
//绘制随机数字
g.drawString(randomString, 18, 20);
//加噪点
for(int i=0 ,n=random.nextInt(100);i<n;i++){
g.drawRect(random.nextInt(100), random.nextInt(30), 1, 1);
}
//输出图片
ImageIO.write(bi,"jpg",response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}