Java generic class for graphic verification Codes

Source: Internet
Author: User

In applications, in order to prevent automatic access by the system from being attacked, a person's eye is usually provided for images that are easy to recognize but difficult to recognize by the program. Some characters are randomly generated in the graphics. To prevent automatic recognition by the attacked program, the characters are usually randomly processed in the position and color.

For ease of use, I use Java to implement a general class for generating random character images, which encapsulates the complexity of the generation process and is very convenient to use.

The implementation class name is randomgraphic. It creates an object instance by using the static factory method createinstance (INT charcount). charcount specifies the number of characters in the image, up to 16.

Two methods are provided to generate a random image. The string drawnumber (string graphicformat, outputstream out) method generates random numbers and consists of 0-9.

In another method, the image generated by string drawalpha (string graphicformat, outputstream out) is a random letter consisting of a-Z. The number of characters generated is specified in the factory method. Separating numbers from images is because the human eyes of some numbers and letters are difficult to distinguish, which affects user input.

Graphicformat is the format of the generated image. The constant value is graphic_jpeg or graphic_png.

Out is used to output the content of the generated image file, which can be a file or a stream output to the client in the servlet for display on the page.

The following shows the source code and the sample code in servlet.

Package net;
Import java. AWT. color;
Import java. AWT. Font;
Import java. AWT. graphics2d;
Import java. AWT. image. bufferedimage;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Io. outputstream;
Import java. util. Random;

Import javax. ImageIO. ImageIO;

/**
* Generate random numbers or serial numbers and display them as images for manual identification, making it difficult for programs to recognize.
* Reduce the possibility that the system will be automatically attacked by programs.
* The Color of the generated image is a random combination of red, black, blue, and purple. The vertical positions of numbers and letters are
* It is also random within a certain range, reducing the chance of being automatically recognized by the program.
* The numbers 0, 1, 2 are easy to confuse with the letters o, L, and Z, making it difficult for human eyes to recognize, so no numbers are generated.
* A mixed string with letters.
* The generated strings and letters are all in lower case. The maximum length of the string is 16.
*
* @ Version
* @ Since
* @ See also
* @ Author lchen
* Create date 2005-12-16
*
*/

Public class randomgraphic {
// Character height and width, in pixels
Private int wordheight = 10;
Private int wordwidth = 15;
// Character size
Private int fontsize = 16;
// Maximum number of strings
Private Static final int max_charcount = 16;
 
// Start position in the vertical direction
Private Final int initypos = 5;
 
 
// The number of characters to be generated, which is obtained by the factory Method
Private int charcount = 0;
 
 
// Color array. A Random value is selected when a string is drawn.
Private Static final color [] char_color = {color. Red, color. Blue, color. Green, color. Magenta };
 
// Random number generator
Private random r = new random ();
 
/**
* The format of the generated image is. jpg;
* When outputting data to a page, you must set the MIME type to image/JPEG.
*/
Public static string graphic_jpeg = "Jpeg ";
/**
* The format of the generated image is regular. The PNG format indicates that the extension name is .png when the file is generated;
* When outputting data to a page, you must set the MIME type to image/PNG.
*/
Public static string graphic_png = "PNG ";
 
 
 
// Create an object using the factory Method
Protected randomgraphic (INT charcount ){
This. charcount = charcount;
}
 
 
/**
* Method for creating an object Factory
* @ Param charcount refers to the number of characters to be generated, ranging from 1 to 16.
*
* Return returns the randomgraphic object instance.
* @ Throws throw when the charcount parameter is incorrect
*/
Public static randomgraphic createinstance (INT charcount) throws exception {
If (charcount <1 | charcount> max_charcount ){
Throw new exception ("invalid parameter charcount, charcount shocould between in 1 and 16 ");
}
Return new randomgraphic (charcount );
}
 
 
/**
* Generate a random number string and draw it as an image. The drawing result is output to the stream out.
*
* @ Param graphicformat: sets the generated image format. The value is graphic_jpeg or graphic_png.
* @ Param out image result output stream
* @ Return the value of the randomly generated string
* @ Throws ioexception
*/
Public String drawnumber (string graphicformat, outputstream out) throws ioexception {
// Randomly generated string value
String charvalue = "";
Charvalue = randnumber ();
Return draw (charvalue, graphicformat, out );

}

/**
* A random sequence string is generated and drawn as an image. The result is output to the stream out.
*
* @ Param graphicformat: sets the generated image format. The value is graphic_jpeg or graphic_png.
* @ Param out image result output stream
* @ Return the value of the randomly generated string
* @ Throws ioexception
*/
Public String drawalpha (string graphicformat, outputstream out) throws ioexception {
// Randomly generated string value
String charvalue = "";
Charvalue = randalpha ();
Return draw (charvalue, graphicformat, out );

}

 
 
 
 
/**
* Draw a string as an image and output the result to the stream out.
* @ Param charvalue the string to be drawn
* @ Param graphicformat: sets the generated image format. The value is graphic_jpeg or graphic_png.
* @ Param out image result output stream
* @ Return the value of the randomly generated string
* @ Throws ioexception
*/
Protected string draw (string charvalue, string graphicformat, outputstream out) throws ioexception {

// Calculate the image width and height
Int W = (charcount + 2) * wordwidth;
Int H = wordheight * 3;

// Create a memory image area
Bufferedimage Bi = new bufferedimage (W, H, bufferedimage. type_3byte_bgr );
Graphics2d G = Bi. creategraphics ();

// Set the background color
Color backcolor = color. White;
G. setbackground (backcolor );
G. fillrect (0, 0, W, H );

// Set Font
G. setfont (new font (null, Font. Bold, fontsize ));
// Draw charvalue, with random color of each character
For (INT I = 0; I <charcount; I ++ ){
String c = charvalue. substring (I, I + 1 );
Color color = char_color [randomint (0, char_color.length)];
G. setcolor (color );
Int xpos = (I + 1) * wordwidth;
// Vertical Random
Int ypos = randomint (initypos + wordheight, initypos + wordheight * 2 );
G. drawstring (C, xpos, ypos );
}
G. Dispose ();
Bi. Flush ();
// Output to the stream
ImageIO. Write (Bi, graphicformat, out );

Return charvalue;
}
 
 
 
 
Protected string randnumber (){
String charvalue = "";
// Generate a random number string
For (INT I = 0; I <charcount; I ++ ){
Charvalue + = string. valueof (randomint (0, 10 ));
}
Return charvalue;
}
 
 
Private string randalpha (){
String charvalue = "";
// Generate a random sequence string
For (INT I = 0; I <charcount; I ++ ){
Char c = (char) (randomint (0, 26) + 'A ');
Charvalue + = string. valueof (C );
}
Return charvalue;
}
 
 
 
/**
* Returns a random integer between [from, ).
*
* @ Param from start value
* @ Param to end value
* @ Return [from, to) is a random integer
*/
Protected int randomint (int from, int ){
// Random r = new random ();
Return from + R. nextint (to-from );
}
 
 
 
/**
* @ Param ARGs
* @ Throws exception
*/
Public static void main (string [] ARGs) throws exception {
 
System. Out. println (randomgraphic. createinstance (5). drawalpha (randomgraphic. graphic_png, new fileoutputstream ("C:/myimg.png ")));


}
 
}

Randomgraphic Class Original code ended

This class is used in servlet to output images to the client, so that random images can be displayed on the page.

Package net;

Import java. Io. ioexception;

Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;

Public class randimage extends httpservlet {

Public randimage (){
Super ();

}

 
 
Protected void doget (httpservletrequest req, httpservletresponse res) throws ioexception, servletexception {

// Set the output content to an image in JPEG format
Res. setcontenttype ("image/jpg ");
Try {
// Output the content to the output stream of the response client object. The generated image contains 6 characters.

String v = randomgraphic. createinstance (6). drawalpha (randomgraphic. graphic_jpeg, res. getoutputstream ());
// Keep the string value in the session to compare it with the verification code manually entered by the user. The comparison is not the focus of this article.

Req. getsession (). setattribute ("rv", V );
} Catch (exception e ){

E. printstacktrace ();
}

}

 
}

You need to configure the servlet in Web. xml

<Servlet>
<Servlet-Name> randimage </servlet-Name>
<Servlet-class> net. randimage </servlet-class>
</Servlet>

<Servlet-mapping>
<Servlet-Name> randimage </servlet-Name>
<URL-pattern>/randimage </url-pattern>
</Servlet-mapping>

Then, use the following code to display the image on a page.

<HTML>
<Body>

Verification Code: <image src = "randimage"/>

</Body>
</Html>

To increase the difficulty of image recognition, you can also perform deformation and rotation of the image to a certain extent in the draw method, or add random interference lines to the image, however, it is necessary to ensure that the human eye can be easily identified.

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.