Generate verification codes with Java graphics

Source: Internet
Author: User

Below is an introduction to the graphics of the API documentation!

GraphicsClass is the abstract base class for all graphics contexts, allowing applications to draw on components that have been implemented on a variety of devices and on closed-screen images.

GraphicsObject encapsulates the state information required for basic rendering operations supported by Java. This status information includes the following properties:

    • The object on which to draw Component .
    • The transition origin for rendering and clipping coordinates.
    • The current clipping area.
    • The current color.
    • The current font.
    • The current logical pixel manipulation function (XOR or Paint).
    • The current XOR alternating color (see setXORMode(java.awt.Color) ).

The coordinates are infinitely subdivided and are located between the pixels of the output device. Drawing outlines is done by using a pixel-sized brush to traverse an infinitely subdivided path between pixels, drawing the brush down and to the right from the anchor point on the path. The action to fill a graphic is to fill the inner area of the graphic with an infinite subdivision path operation. The action of rendering horizontal text is to render the ascending portion of a character glyph that is completely above the baseline coordinates.

Drawing brushes draw downward and right from the path you want to traverse. It has the following meanings:

    • If you draw a shape that overrides a given rectangle, the shape occupies more than one row of pixels on the right and bottom side, compared to the shape that the fill is bounded by the same rectangle.
    • If you draw a horizontal line along the same y -coordinate as a line of text baselines, it is completely drawn below the text except for all the descending parts of the text.

All the Graphics coordinates that appear as arguments to this object method are relative to the origin of this object before the method is called Graphics .

All render operations only modify pixels within the bounds of the current clip, which is specified by the user space Shape and controlled by the program that uses Graphics the object. This user's clipboard is converted to device space and is combined with the device's clipboard , which is defined by window visibility and device scope. The combination of the user's clipboard and the device's clipboard defines the composite clipping area, which determines the final clipping area. The user's clipboard cannot be modified by the rendering system to reflect the resulting composite clipping area. The user's clipboard can only be setClip changed by or by clipRect method. All drawing or writing is done in the current color, the current drawing mode, and the current font.

Graphical verification codes are used for user authentication on Web pages to prevent non-registered users from using brute force hack to get passwords or bulk registrations! Using Java graphics to generate a graphics verification code or it's very simple. Let's look at the code below!

The main code is placed in the servlet's Get method.

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

Response.setcontenttype ("Image/jpeg");
HttpSession session = Request.getsession ();
int width = 100;
int height=40;
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
Create a memory image and get its graphics context
BufferedImage image =new BufferedImage (width, height, bufferedimage.type_int_rgb);
Graphics g = image.getgraphics ();
Generate Random Codes
A character descriptor that defines a random code
String chars= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] Rands = new Char[4];
for (int i=0;i<4;i++) {
int rand = (int) (Math.random () *36);
Rands[i] =chars.charat (RAND);

Generating images
Draw a background

}

G.setcolor (New Color (0xDCDCDC));
G.fillrect (0, 0, width, height);
for (int i=0;i<500;i++) {
int x= (int) (Math.random () *width);
int y= (int) (Math.random () *height);
int red= (int) (Math.random () *255);
int green= (int) (Math.random () *255);
int blue= (int) (Math.random () *255);
G.setcolor (New Color (Red,green,blue));
G.drawoval (x, y, 1, 0);
}
G.setcolor (Color.Black);
G.setfont (New Font (null,font.italic,30));
Different characters for output verification codes at different heights
G.drawchars (rands, 0, 1, 1, 35);
G.drawchars (rands,1,1, 24, 30);
G.drawchars (rands,2,1, 42, 25);
G.drawchars (rands,3,1, 57, 32);
G.drawchars (rands,4,1, 61, 19);
G.drawchars (rands,5,1, 76, 22);
G.dispose ();
outputting an image to the client
Servletoutputstream SOS = Response.getoutputstream ();
Bytearrayoutputstream BAOs =new bytearrayoutputstream ();
Imageio.write (Image, "JPEG", BAOs);
byte[] buffer = Baos.tobytearray ();
Response.setcontentlength (buffer.length);
Sos.write (buffer);
Baos.close ();
Sos.close ();
Put validation into session
Session.setattribute ("Checkcode", New String (Rands));
}

This is just one of many ways to generate CAPTCHA, and it's relatively simple! In fact, using the graphics class can generate more complex verification code, friends can try it yourself!

Generate verification codes with Java graphics

Related Article

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.