<%@page import="java.awt.*, java.awt.image.*, java.util.*, javax.imageio.*" %><%!
// 函数只能在声明块中定义
Color getRandColor(int fc, int bc) {
Random random = new Random();
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);
Color clr = new Color(r, g, b);
return clr;
}
%><%
response.setContentType("image/png");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 75;
int height = 25;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建图像
Graphics graphics = image.getGraphics();
graphics.setColor(getRandColor(200, 250));
graphics.fillRect(0, 0, width, height); // 填充背景色
graphics.setColor(getRandColor(160, 200));
graphics.drawRect(0, 0, width - 1, height - 1); // 画边框
int i;
Random random = new Random();
graphics.setColor(getRandColor(160, 200));
for (i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
graphics.drawLine(x, y, x + x1, y + y1);
}
// 取随机产生的认证码(4位数字)
String str = "";
Font font = new Font("Times New Roman", Font.PLAIN, 24);
graphics.setFont(font);
for (i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
str += rand;
Color clr = new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110));
graphics.setColor(clr);
graphics.drawString(rand, 13 * i + 14, 20);
}
session.setAttribute("vcode", str);
graphics.dispose();
ImageIO.write(image, "PNG", response.getOutputStream());
%>