One: Demand analysis
To generate a verification code using Java:
1: Create a canvas and draw a good background image
2: Draw Random numbers
3: Draw the interfering line
4: Save the In-memory picture to your hard disk
Two: The code is as follows
1 /**2 * 3 */4 PackageCom.hlcui.io;5 6 ImportJava.awt.Color;7 ImportJava.awt.Font;8 ImportJava.awt.Graphics;9 ImportJava.awt.image.BufferedImage;Ten ImportJava.io.File; One Importjava.io.IOException; A ImportJava.util.Random; - - ImportJavax.imageio.ImageIO; the - /** - * @authorAdministrator Generate verification Code - */ + Public classValidatecode { - //defines the width and height of the canvas + Public Static Final intWIDTH = 300; A Public Static Final intHEIGHT = 150; at Public Staticbufferedimage bi; - Public StaticGraphics G; - Public StaticRandom r =NewRandom (); - - //generate a random number between min to Max - Private Static intRintMinintmax) { in intnum = R.nextint (max-min) +min; - returnnum; to } + - //Drawing background picture the Public Static voidGeneratebg () { *BI =Newbufferedimage (WIDTH, HEIGHT, Bufferedimage.type_int_rgb); $g =bi.getgraphics ();Panax NotoginsengG.setcolor (NewColor (r (0, 255), R (0, 255), R (0, 255));//set the background color of the canvas -G.fillrect (0, 0, WIDTH, HEIGHT);//Fill the } + A //Draw Random Numbers the Public Static voidGeneratenum () { +String words = "abcdefghijklmnopqrstuvwxyz0123456789"; - for(inti = 0; I < 4; i++) { $G.setcolor (NewColor (r (0, 255), R (0, 255), R (0, 255))); $G.setfont (NewFont ("Microsoft Jas Black", Font.plain, 70)); - Charc = Words.charat (r (0, Words.length ())); -g.DrawString (String.valueof (c), + I *, R (HEIGHT-40)); the } - }Wuyi the //Draw Interference Lines - Public Static voidGenerateline () { Wu for(inti = 0; I < 25; i++) { -G.setcolor (NewColor (r (0, 255), R (0, 255), R (0, 255))); AboutG.drawline (r (0, width), R (0, HEIGHT), R (0, width), R (0, HEIGHT)); $ } - } - - //output pictures from memory to hard disk A Public Static voidSave ()throwsIOException { +File File =NewFile ("F:/1.png"); theImageio.write (BI, "PNG", file); -System.out.println ("Save done! "); $ } the the //Test the Public Static voidMain (string[] args)throwsIOException { the GENERATEBG (); - generatenum (); in generateline (); the save (); the } About}
Three: Generate Captcha picture
All of the above codes have been verified!
Java Generate Verification Code