四位验证码生成,其中字符随机,字体大小,类型以及位置随机,背景为彩色随机。
<%@ page contentType="image/jpeg" autoFlush="false" import="java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*,javax.imageio.*"%>
<%
/*生成的验证码字符范围*/
String chose = "23456789abdefghijmnqrtyABDEFGHJLMNQRTY";
/*显示验证码内容*/
char display[] = {'0',' ','0',' ','0',' ','0'},
ran[] = {'0','0','0','0'},
temp;
/*随机选择认证码*/
Random rand = new Random();
for(int i=0;i<4;i++){
temp=chose.charAt(rand.nextInt(chose.length()));
display[i*2]=temp;
ran[i]=temp;
}
//String random=String.valueOf(display);
/*保存产生的认证码*/
session.setAttribute("verify_code",String.valueOf(ran));
%>
<%
out.clear();
response.setContentType("image/jpeg");
response.addHeader("pragma","NO-cache");
response.addHeader("Cache-Control","no-cache");
response.addDateHeader("Expries",0);
int width=140, height=40; //认证码显示的范围
Random tmpRand = new Random(); //随即生成数字
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
/*Graphics2D g = (Graphics2D)image.getGraphics();*/
/*背景处理*/
Color bkgrdColor;
/*分成N列*/
int widthFlag = 5 + tmpRand.nextInt(20);
/*分成M行*/
int heightFlag = 0;
int SranWidth = 0, SranHeight = 0;
/*绘制方格*/
//Random a = new Random();
/*处理背景色为白色*/
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
/*填充背景格子颜色*/
for(int i=0; i<widthFlag; i++){
SranWidth = i * ( (width + 10) / widthFlag );
heightFlag= 5 + tmpRand.nextInt(8);
for(int j=0; j<heightFlag; j++){
SranHeight = j * ( (height + 10) / heightFlag );
bkgrdColor = new Color(100+tmpRand.nextInt(155),100+tmpRand.nextInt(155),100+tmpRand.nextInt(155));
//bkgrdColor = new Color( 1+(int)Math.random()*79,1+(int)Math.random()*79,1+(int)Math.random()*79 );
//
bkgrdColor.brighter();
g.setColor(bkgrdColor);
g.fillRect(SranWidth, SranHeight, width/widthFlag, height/heightFlag);
}
}
/*随机画一条线*/
g.setColor(Color.BLACK);
g.drawLine(tmpRand.nextInt(width),tmpRand.nextInt(height),tmpRand.nextInt(width),tmpRand.nextInt(height));
/*字处理*/
String[] font={"Clarendon Condensed","Comic Sans MS","Times New Roman","Palatino Linotype","Monotype Corsiva"};
Color fontColor;
int fontFlag = 0; //选择字体的类型
int fontSize = 18;//选择字体的大小
for(int i=0; i<display.length; i++){
fontFlag = tmpRand.nextInt(4);
fontSize = 22 + tmpRand.nextInt(18) ;
g.setFont(new Font(font[fontFlag],Font.BOLD,fontSize));
fontColor = new Color( tmpRand.nextInt(100),tmpRand.nextInt(100),tmpRand.nextInt(100) );
g.setColor(fontColor);
g.drawChars(display,i,1,15*i+8,30 + tmpRand.nextInt(5));
}
g.dispose();
ImageIO.setUseCache(false);
ImageIO.write(image, "JPEG", response.getOutputStream());