Register the image verification code in java

Source: Internet
Author: User

Register the image verification code in java
Package org. servlet. demo;

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. nio. charset. Charset;
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;

Public class DrawImageServlet extends HttpServlet {
/**
* On the user logon page, a random digit verification is required to prevent malicious attacks.
*
*/
// Define the image width and height
Public static finals int WIDTH = 200;
Public static final int HEIGHT = 50;

Protected void doGet (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {

// Create an image BufferedImage. TYPE_INT_RGB to set the image type
BufferedImage image = new BufferedImage (WIDTH, HEIGHT,
BufferedImage. TYPE_INT_RGB );
// Get the image's paint brush
Graphics g = image. getGraphics ();
// Set the background color of the image
SetBackGround (g );
// Set the border of the image
SetBorder (g );
// Sketch the interference lines on the Image
DrawRandomLine (g );
// Write a random number to the image
WriteRandomNum (g );

// Tell the browser the write type
Resp. setContentType (image/jpeg );
// Write the image to the browser
ImageIO. write (image, jpg, resp. getOutputStream ());
// Do not cache the browser with header Control
Resp. setDateHeader (expries,-1 );
Resp. setHeader (Cache-Control, no-cache );
Resp. setHeader (Pragma, no-cache );
}

Private void writeRandomNum (Graphics graphics ){
/** [1-regular] is the interval Regular Expression of Chinese Characters
\ U indicates that an uncode table exists.
It means that all Chinese characters are in the U (uncode) code table between 4e00 and 9fa5 */
String base =
One of them is that I don't come here. He just went to the upper reaches and said, son +
It's also up to you to check whether the day is good or not. +
Just as the Lord would like to give birth to the old Ten from the front of its first line, it then looks like seeing +
Dual-Purpose: she made the move into something to do, and she had already sent jobs to the mountain masses. +
I want to give changshui a few meanings and give it a voice in the hands of the experts, the eyes, the snacks, the war of two questions, but the body is solid +
What do you do? When you listen to the leather, it's really the only four that are already the best enemy!
In the vernacular East Xi times, if the child is put in the mouth of the flower, the fifth step is to write the military, and then send the text to the fruit +
How can we make sure that the fast and bright line will not fly outside the tree and the living department will not lead the team to the ship? +
When the end of the station on behalf of the machine more 9 you every wind level with a smile Ah ten children less than the Italian night than the order +
Even when the car is heavy, Which of the following is too much to change to the social media, the dry stone, the day of the battle, the hundred yuan naqun +
The six books explain the eight difficulties in the village of lihe. The root of the discussion is to study the book together. +
Answer the response and check the back part of the message to search for the attacker or students to run together.
Zhunzhang tuanwu is away from the color face film, and the eye is shining to the world, and the night table of the star guide is enough to recognize +
Call the world to draw a name. tuqingyang shall follow the history and change the history to create a mouth. This rule shall be applied to the north. +
Rain wear internal identification pass industry food climb sleep Xingxing volume view bitter body all traffic break through +
Youdu shifan's sub-room, very South gun, read the Sha old line, ye jiankong, and calculate it to Zhengcheng +
Lao Qian tewei's younger brother wins the education hot show pack song class is getting stronger and more popular
The old God's seat helps the system to jump beyond the power of the ox to access the bank and dare to drop the installation. +
I love to wait for the study to fear the hope of the Moon and the half-fire method.
Top urgent Forest Stop sentence area clothing like report ye pressure slow uncle back fine +
When the snow was not playing well, ping wei was very busy mentioning that it was close to the bright light to emphasize nangu black;
// The method in Graphics2D can be used to set the rotation radians.
Graphics2D g = (Graphics2D) graphics;
// Set the font color
G. setColor (Color. RED );
// Set the Font Style
G. setFont (new Font (, Font. BOLD, 30 ));
// Write four men
Int x = 10;
For (int I = 0; I <4; I ++ ){
// Set the font radians
Double d = new Random (). nextInt () % 30;
String target = String. valueOf (base. charAt (new Random (). nextInt (base. length ())));
// Set the font radians
G. rotate (d * Math. PI/180, x, 35 );
// The font is written in the rectangle, and the font space and the font coordinates need to be considered. The y mark remains unchanged.
G. drawString (target, x, 35 );
// Callback the font radians. Otherwise, the next font will be rotated.
G. rotate (-d * Math. PI/180, x, 35 );
// The font size is 20, with no interval of 10.
X + = 45;
}

}
// Sketch the interference lines on the Image
Private void drawRandomLine (Graphics g ){
G. setColor (Color. GREEN); // sets the Color of the interfering line.
// Sketch 10 interference lines
For (int I = 0; I <10; I ++ ){

// The initial Coordinate Position of the sketch line, which must be within the image size
Int x1 = new Random (). nextInt (WIDTH );
Int y1 = new Random (). nextInt (HEIGHT );
// End Coordinate
Int x2 = new Random (). nextInt (WIDTH );
Int y2 = new Random (). nextInt (HEIGHT );
G. drawLine (x1, y1, x2, y2 );
}

}

// Set the border color
Private void setBorder (Graphics g ){
G. setColor (Color. BLUE );
G. drawRect (1, 1, WIDTH-2, HEIGHT-2 );
}

// Set the background color of the image.
Private void setBackGround (Graphics g ){
G. setColor (Color. WHITE); // WHITE
G. fillRect (0, 0, WIDTH, HEIGHT); // fill in the image color

}

@ Override
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
DoGet (req, resp );
}

}

 

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.