1. Generate Verification Code tool class
Public classCheckcodetool {PrivateInteger width = 80; PrivateInteger height = 38; PublicString Getcheckcode (baseform baseform) {/** Drawing*/ //Step1, create a Memory image object (artboard)BufferedImage image =Newbufferedimage (width, height, bufferedimage.type_int_rgb); //Step2, getting brushesGraphics g =Image.getgraphics (); //step3, coloring a pen//random R = new Random ();SecureRandom r =NewSecureRandom (); //G.setcolor (New Color (R.nextint (255), R.nextint (255), R.nextint (255))); //Step4, setting the background color for the artboardG.fillrect (0, 0, width, height); //Step5, draw a random stringString number =GetNumber (); G.setcolor (NewColor (0, 0, 0)); //Storage to Redis (for login verification) if(BaseForm! =NULL&&Stringutils.isnotempty (Baseform.getsessionid ())) {String Redischeckcodeid= "Checkcodeid"; Try { if(Redisutil.getinstance (). Isexists (Redischeckcodeid)) {redisutil.getinstance (). Remove (Redische Ckcodeid); } redisutil.getinstance (). Setstringwithseconds (Redischeckcodeid,number,60);//1 minute prescription}Catch(Exception e) {System.out.println ("Getcheckcode:error:" +e.tostring ()); } } //New Font (font, style, size)G.setfont (NewFont (NULL, Font.Italic, 20)); g.DrawString (number,5, 25); //Step6, add some interference lines. for(inti = 0; I < 8; i++) {G.setcolor (NewColor (R.nextint (255), R.nextint (255), R.nextint (255))); G.drawline (R.nextint (width), r.nextint (height), r.nextint (width), r.nextint (height)); } /** Compress picture and output to client (browser)*/Bytearrayoutputstream out=NewBytearrayoutputstream (); String base64string= ""; Try{imageio.write (image,"JPEG", out); Base64string=Base64utils.encode (Out.tobytearray ()); } Catch(Exception e) {e.printstacktrace (); } finally { if(Out! =NULL) { Try{out.close (); } Catch(IOException e) {e.printstacktrace (); } } } returnbase64string; } //generate a random number as a verification code Privatestring GetNumber () {string number= ""; String Pool= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; SecureRandom R=NewSecureRandom (); for(inti = 0; I < 4; i++) { number+=Pool.charat (R.nextint (Pool.length ())); } returnNumber ; }}
2. Test Verification Class
Public class checkcodetest { publicstaticvoid main (string[] args) { // TODO auto-generated method stub new checkcodetool (); = Checkcodetool.getcheckcode (new baseform ()); System.out.println (Checkcode); }}
Output:
/9J/4AAQSKZJRGABAGAAAQABAAD/2WBDAAGGB ...
The base64string string is passed to the front end to display the picture verification code.
Java uses ImageIO, AWT to generate picture verification code