//设置宽高
int width = 100;
int height = 50;
//创建图片对象
BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
//创建画笔对象
Graphics grap = img.getGraphics();
//设置颜色
grap.setColor(Color.white);
//填充背景色
grap.fillRect(0,0,width,height);
grap.setColor(Color.red);
//创建边框
grap.drawRect(0,0,width-1,height-1);
grap.setColor(Color.black);
//创建字符集
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
//写字符,随机生成字符
for (int i = 1; i <= 4; i++) {
int index = random.nextInt(str.length());
char ch = str.charAt(index);
grap.drawString(ch+"",width/5*i,height/2);
}
grap.setColor(Color.pink);
//绘制干扰线,两点确定一线
for (int i = 0; i < 8; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
grap.drawLine(x1,x2,y1,y2);
}
//输出验证码图片
ImageIO.write(img,"jpg",resp.getOutputStream());
里面的各种颜色可以随意改变,按自己的喜好来进行,这是写在servlet中的代码块