public static Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
Random random = new Random();
if (fc > 255)
fc = 255;
if (fc > 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);
}
/** StringBuffer 类型的参数,参数传递方式为“传引用”,方法中对StringBuffer 的更改,方法外也更改**/
public static BufferedImage makeValidatePic(StringBuffer validateCode) {//图片生成代码
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(getRandColor(200, 250)); //设置背景颜色 200.200.200RGB值,接近白色
g.fillRect(0, 0, width, height);
Random random = new Random();
g.setColor(getRandColor(160, 200)); //画干扰线 比背景色要深
for (int i = 0; i < 155; i++) {
int px = random.nextInt(width);
int py = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(px, py, px + xl, py + yl);
}
for (int i = 0; i < 4; i++) {
Font font = new Font("Times New Roman", Font.PLAIN, 18); //设置验证码字体
g.setFont(font);
g.setColor(getRandColor(20, 100));
int num = random.nextInt(10); //取随机数字
validateCode.append(num); //记录随机数字
int x = 6 + 13*i; //设置每个数字的坐标
int y = 16;
g.drawString(num + "", x, y);
}
g.dispose();
return image;
}
public static String makeValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
StringBuffer validateCode = new StringBuffer();
BufferedImage image = makeValidatePic(validateCode);
ImageEncoder imageEncoder = ImageEncoderFactory.newInstance(ImageFormat.JPEG);
String sessionId = (String) request.getSession().getAttribute("validateSessionId");
saveValidateCode(validateCode.toString(), sessionId);//记录验证码值。存数据库,或者记入SESSION中
response.setHeader("Pragma", "no-cache"); //设置验证码不缓存,否则有些情况下浏览器会缓存验证码图片
response.setHeader("Cache-Control", "no-cache,must-revalidate");
response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:01 GMT");
OutputStream out =response.getOutputStream(); //输出图片
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}