生成图片验证码
private ImageCode createImageCode(HttpServletRequest request) {
int width = ServletRequestUtils.getIntParameter(request, Constants.WIDTH,
securityProperties.getValidateCode().getImage().getWidth());
int height = ServletRequestUtils.getIntParameter(request, Constants.HEIGHT,
securityProperties.getValidateCode().getImage().getHeight());
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
Random random = new Random();
graphics.setColor(randomColor(200, 250));
graphics.fillRect(0, 0, width, height);
graphics.setFont(new Font(securityProperties.getValidateCode().getImage().getFontName(),
Font.ITALIC,
securityProperties.getValidateCode().getImage().getFontSize()));
for (int i = 0; i < 155; i++) {
graphics.setColor(randomColor(160, 200));
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sRand = new StringBuilder();
Integer randLength = securityProperties.getValidateCode().getImage().getLength();
for (int i = 0; i < randLength; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand.append(rand);
graphics.setColor(randomColor(20, 130));
graphics.drawString(rand, 13 * i + 6, 16);
}
graphics.dispose();
return new ImageCode(image, sRand.toString(),
securityProperties.getValidateCode().getImage().getExpireSeconds());
}
private Color randomColor(int fc, int bc) {
Random random = new Random();
int max = 255;
if (fc > max) {
fc = max;
}
if (bc > max) {
bc = max;
}
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);
}