int width = 120;
int height = 25;
BufferedImage image = new BufferedImage(120, 25, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 边线
g.setColor(Color.GREEN);
g.drawRect(0, 0, width, height);
// 填充颜色
g.setColor(Color.YELLOW);
g.fillRect(1, 1, width - 2, height - 2);
// 干扰线
g.setColor(Color.GRAY);
Random r = new Random();
for (int i = 0; i < 9; i++)
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
g.setColor(Color.RED);
// Font.BOLD|Font.ITALIC 粗体加斜体
g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 15));
int x = 20;
for (int i = 0; i < 4; i++) {
String num = r.nextInt(10) + " ";
g.drawString(num, x, 20);
x += 20;
}
ImageIO.write(image, "jpg", response.getOutputStream());
这种方法是自己创建验证码的样式。
还有一种方法是使用已经建好的包ValidateCode.jar
ValidateCode vc = new ValidateCode(120, 25, 4, 9);
vc.write(response.getOutputStream());
也可以生成。