Java generates Verification Code Image
Public class AuthImg extends HttpServlet {
/**
*
*/
Private static final long serialVersionUID = 4975974534946437434L;
// Set the font and size of the graphic verification code string
Private Font mFont = new Font ("", Font. ITALIC, 18 );
Private Random random = new Random ();
Public void init () throws ServletException {
Super. init ();
}
// Service method for generating Server Response
Public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Prevents the generated page from being cached to ensure that a new verification code is generated each time.
Response. setHeader ("Pragma", "No-cache ");
Response. setHeader ("Cache-Control", "no-cache ");
Response. setDateHeader ("Expires", 0 );
Response. setContentType ("image/jpeg ");
// Specify the size of the Verification Code Image
Int width = 80, height = 24;
// Generate a new image
BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_3BYTE_BGR );
// Draw content in the image
Graphics g = image. getGraphics ();
G. setColor (new Color (252,252,252 ));
G. fillRect (1, 1, width, height );
G. setColor (new Color (252,252,252 ));
G. drawRect (0, 0, width, height );
G. setFont (mFont );
G. setColor (new Color (252,252,252 ));
// This variable is used to save the random variable string generated by the system.
String sRand = "";
Int colorR = random. nextInt (200 );
Int colorG = random. nextInt (200 );
Int colorB = random. nextInt (200 );
For (int I = 0; I <4; I ++ ){
// Obtain a random string
String tmp = getRandomChar ();
SRand + = tmp;
// Add the random string generated by the system to the image
G. setColor (new Color (colorR, colorG, colorB ));
G. drawString (tmp, 15 * I + 10, 20 );
}
// Obtain the user's Session
HttpSession session = request. getSession (true );
// Add the Random verification code generated by the system to the user Session
Session. setAttribute ("rand", sRand );
G. dispose ();
// Output the verification code Image
ImageIO. write (image, "JPEG", response. getOutputStream ());
}
// Method for generating random strings
Private String getRandomChar (){
Int itmp = random. nextInt (10 );
Return String. valueOf (itmp );
}
}