Java generates a random Verification Code

Source: Internet
Author: User
Import java. AWT. color;
Import java. AWT. Font;
Import java. AWT. graphics;
Import java. AWT. image. bufferedimage;
Import java. Io. file;
Import java. util. Random;

Import javax. ImageIO. ImageIO;

/**
* Codeimagegenerator. Java
*
* @ Author <a href = "mailto: eroclu@gmail.com"> Andy Lu </a>
* @ Version 1.0
*/
Public final class codeimagegenerator {
Private Final Static int def_width = 60;
Private Final Static int def_height = 20;

Private string code;
Private int width;
Private int height;
Private bufferedimage image;

Public codeimagegenerator (){
This (def_width, def_height );
}

Public codeimagegenerator (INT width, int height ){
This. width = width;
This. Height = height;
Generatecodeimage ();
}

Private void generatecodeimage (){
// Create the image
Image = new bufferedimage (width, height, bufferedimage. type_int_rgb );
Graphics G = image. getgraphics ();

// Set the background color
G. setcolor (new color (0 xdcdcdc ));
G. fillrect (0, 0, width, height );

// Draw the border
G. setcolor (color. Black );
G. drawrect (0, 0, width-1, height-1 );

// Set the font
G. setfont (new font ("Times New Roman", Font. Plain, 18 ));

// Create a random instance to generate the Codes
Random random = new random ();

// Make some confusion
For (INT I = 0; I <50; I ++ ){
Int x = random. nextint (width );
Int y = random. nextint (height );
G. drawoval (X, Y, 0, 0 );
}

// Generate a random code
For (INT I = 0; I <4; I ++ ){
String Rand = string. valueof (random. nextint (10 ));
Code + = rand;
G. drawstring (RAND, 13 * I + 6, 16 );
}

G. Dispose ();
}

Public bufferedimage getimage (){
Return image;
}

Public String getcode (){
Return code;
}

Public static void main (string [] ARGs) throws exception {
File imgfile = new file ("codeimage.jpeg ");
Codeimagegenerator CIG = new codeimagegenerator ();
ImageIO. Write (CIG. getimage (), "Jpeg", imgfile );
}
}
 

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.