代码如下:
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
// 定义验证码边框的长和高
int width = 60;
int height = 20;
// 定义图片缓冲区,使用RGB模式输出图片
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 定义画笔工具对象
Graphics graph = img.getGraphics();
// 设置验证码框的背景颜色
graph.setColor(new Color(200, 200, 200));
// 使用上面设置的颜色填充整个矩形框
graph.fillRect(0, 0, width, height);
// 定义要显示的验证码
StringBuffer codeStr = new StringBuffer("");
// 定义验证码数组
String code[] = { "A", "a", "B", "b", "C", "c", "D", "d", "E", "e",
"F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k",
"L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q",
"R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w",
"X", "x", "Y", "y", "Z", "z", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "0", "1" };
// 定义随机数对象
Random rnd = new Random();
// 使用for循环生成随机数,使用随机数从数组中取出字符作为验证码
for (int i = 0; i < 4; i++) {
//每循环一次取出一个字符
String cStr = code[rnd.nextInt(104)];
//设置每一个输出的验证码的颜色
graph.setColor(new Color(rnd.nextInt(125),rnd.nextInt(125),rnd.nextInt(125)));
//设置输出验证码的字体
graph.setFont(new Font("",Font.PLAIN,20+rnd.nextInt(5)));
//绘制每一个验证码
graph.drawString(cStr, 15*i+rnd.nextInt(5), 20-rnd.nextInt(5));
//将每一个验证码添加到整体验证码中
codeStr.append(cStr);
}
//定义验证码字符串
String codeInfo = codeStr.toString();
//将验证码放在session中
request.getSession().setAttribute("code", codeInfo);
//随机产生100个干扰点
for (int i = 0; i < 100; i++)
{
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
graph.setColor(new Color(rnd.nextInt(185)+40,rnd.nextInt(185)+40,rnd.nextInt(185)+40));
//设置干扰点的位置长宽
graph.drawOval(x, y, 1, 1);
}
//将图片输出到页面上
ImageIO.write(img, "JPEG", out);
out.flush();
out.close();