Copy codeThe Code is as follows: package cn. response;
Import java. awt. Color;
Import java. awt. Font;
Import java. awt. Graphics;
Import java. awt. Graphics2D;
Import java. awt. image. BufferedImage;
Import java. io. IOException;
Import java. util. Random;
Import javax. imageio. ImageIO;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
@ SuppressWarnings ("serial ")
Public class validatePicture extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Try {
Validateimage (request, response );
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}
Public static finals int WIDTH = 120;
Public static final int HEIGHT = 25;
Public void validateimage (HttpServletRequest request,
HttpServletResponse response) throws Exception {
BufferedImage bi = new BufferedImage (WIDTH, HEIGHT,
BufferedImage. TYPE_INT_RGB); // create an image in the memory
Graphics g = bi. getGraphics ();
SetBackGround (g); // sets the background color.
SetBorder (g); // set the border
DrawRandomLine (g); // draw interference lines
String random = drawRandomNum (Graphics2D) g); // write a random number.
Request. getSession (). setAttribute ("random", random );
// Request. getSession (false );
Response. setContentType ("image/jpeg ");
// Set not to cache
Response. setDateHeader ("expries",-1 );
Response. setHeader ("Cache-Control", "no-cache ");
ImageIO. write (bi, "jpg", response. getOutputStream ());
}
Private String drawRandomNum (Graphics2D g ){
G. setColor (Color. RED );
G. setFont (new Font ("", Font. BOLD, 20 ));
// [\ U4e00-\ u9fa5] Chinese digit range
String base = "\ u4e00 \ u4f00 \ u5e00 \ u4e50 \ u4e89 \ u4f10 \ u4e09 ";
StringBuffer sb = new StringBuffer ();
Int x = 5;
For (int I = 0; I <4; I ++ ){
Int degree = new Random (). nextInt () % 30;
String ch = base. charAt (new Random (). nextInt (base. length () + "";
Sb. append (ch );
G. rotate (degree * Math. PI/180, x, 20 );
G. drawString (ch, x, 20 );
G. rotate (-degree * Math. PI/180, x, 20 );
X = x + 30;
}
System. out. println (sb. toString ());
Return sb. toString ();
}
Private void drawRandomLine (Graphics g ){
G. setColor (Color. GREEN );
For (int I = 0; I <3; I ++ ){
Int x1 = new Random (). nextInt (WIDTH );
Int y1 = new Random (). nextInt (HEIGHT );
Int x2 = new Random (). nextInt (WIDTH );
Int y2 = new Random (). nextInt (HEIGHT );
G. drawLine (x1, y1, x2, y2 );
}
}
Private void setBorder (Graphics g ){
G. setColor (Color. BLUE );
G. drawRect (1, 1, WIDTH-2, HEIGHT-2 );
}
Private void setBackGround (Graphics g ){
G. setColor (Color. WHITE );
G. fillRect (0, 0, WIDTH, HEIGHT );
}
}