您的位置:首页 > 其它

Servlet实现图片验证码

2015-07-30 15:51 393 查看
public static final char[] CHARS = { '0', '1', '2', '3', '4', '5', 'A',

'B', 'C', 'D' };

public static Random random = new Random();

public static String getRandomString() {

StringBuffer buffer = new StringBuffer();

for (int i = 0; i < 4; i++) {

buffer.append(CHARS[random.nextInt(CHARS.length)]);

}

return buffer.toString();

}

public static Color getRandomColor() {

return new Color(random.nextInt(255), random.nextInt(255),

random.nextInt(255));

}

public static Color getReverseColor(Color c) {

return new Color((255 - c.getRed()), (255 - c.getGreen()),

(255 - c.getBlue()));

}

String randomString = getRandomString();

request.getSession(true).setAttribute("randomString", randomString);

int width = 100;

int height = 30;

Color color = getRandomColor();

Color reverse = getReverseColor(color);

BufferedImage bi = new BufferedImage(width, height,

BufferedImage.TYPE_INT_BGR);

Graphics2D g = bi.createGraphics();

g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));

g.setColor(color);

g.fillRect(0, 0, width, height);

g.setColor(reverse);

g.drawString(randomString, 18, 20);

for (int i = 0, n = random.nextInt(100); i < n; i++) {

g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);

}

ServletOutputStream out = response.getOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode(bi);

out.flush();

<img alt="abc" src="servlet/IdentityServlet" id="identity" onload="btn.disable = false;" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: