---------------------------------------------------------------------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg"
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!//生成随机颜色
Color getRandColor(Random random, int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
//生成随机字符
private String getRandChar() {
int rand = (int) Math.round(Math.random() * 2);
long itmp = 0;
char ctmp = '\u0000';
//根据rand的值来决定是生成一个大写字母、小写字母还是数字
switch (rand) {
//生成大写字母
case 1:
itmp = Math.round(Math.random() * 25 + 65);
ctmp = (char) itmp;
return String.valueOf(ctmp);
//生成小写字母
case 2:
itmp = Math.round(Math.random() * 25 + 97);
ctmp = (char) itmp;
return String.valueOf(ctmp);
//生成数字
default:
itmp = Math.round(Math.random() * 9);
return String.valueOf(itmp);
}
}
//产生随机字体
private Font getFont() {
Random random = new Random();
Font font[] = new Font[5];
font[0] = new Font("Ravie", Font.PLAIN, 18);
font[1] = new Font("Antique Olive Compact", Font.PLAIN, 18);
font[2] = new Font("Forte", Font.PLAIN, 18);
font[3] = new Font("Wide Latin", Font.PLAIN, 18);
font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 18);
return font[random.nextInt(5)];
}%>
<%
//阻止生成的页面内容被缓存,保证每次重新生成验证码
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
//指定验证码图片的大小
int width = 70;
int height = 20;
//生成一张新图片
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_BGR);
//在图片中绘制内容
Graphics g = image.getGraphics();
Random random = new Random();
// 设定图像背景色(因为是做背景,所以偏淡)
//g.setColor(getRandColor(random, 200, 250));
g.fillRect(0, 0, width, height);
//设置图形验证码中字符串的字体和大小
//g.setFont(new Font("Forte", Font.PLAIN, 20));
g.setFont(getFont());
//随机产生10条干扰线,使图象中的认证码不易被其它
程序探测到
for (int i = 0; i < 10; i++) {
int y = random.nextInt(height);
int y1 = random.nextInt(height);
g.setColor(getRandColor(random, 160, 200));
g.drawLine(1, y, width, y1);
}
//该变量用于保存系统生成的随机字符
String sRand = "";
for (int i = 0; i < 4; i++) {
//取得一个随机字符
String tmp = getRandChar();
sRand += tmp;
//将
系统生成的随即字
符添加到图形验证码图片上
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(tmp, 15 * i + 5, 15);
}
//取得用户session
session.setAttribute("code", sRand);
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>