主要是在一个BufferedImage上画上验证码,然后使用ImageIO将图片通过响应输出流输出到页面
int width=100;
int height=35;
BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=bi.getGraphics();
Random random=new Random();
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
Font font=new Font("Times NewRoman",Font.PLAIN,30);
g.setFont(font);
g.setColor(Color.BLACK);
g.drawRect(0,0,width-1,height-1);
g.setColor(Color.GRAY);
//画划痕
for(int i=0;i<160;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(20);
int y1=random.nextInt(20);
g.drawLine(x,y,x1+x,y1+y);
}
//产生一个验证码,见下一个代码快
String validateCode= ToolUtil.validateCode(4, 2);
int red=0,green=0,blue=0;
for(int i=0;i<4;i++){
red=random.nextInt(110);
green=random.nextInt(50);
blue=random.nextInt(50);
g.setColor(new Color(red,green,blue));
g.drawString(String.valueOf(validateCode.charAt(i)),20*i+6,25);
}
session.setAttribute("imgcode",validateCode);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream sos=null;
try {
sos=response.getOutputStream();
ImageIO.write(bi, "jpeg", sos);
sos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sos != null) {
try {
sos.close();
} catch (IOException e) {
}
}
}
/**
* way 1代表只有数字 2代表数字加字母
* num代表数量
* @param num
* @param way
* @return
*/
public static String validateCode(int num,int way){
String code="0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
int max;
char ch;
StringBuffer validateCode=new StringBuffer();
ThreadLocalRandom random=ThreadLocalRandom.current();
if(way==1){
max=10;
}else{
max=62;
}
for(int i=0;i<num;i++){
ch=code.charAt(random.nextInt(0,max));
validateCode.append(ch);
}
return validateCode.toString();
}