Java Generate CAPTCHA Code

Source: Internet
Author: User
Tags set background

Generate Base64 format Picture Verification code

1  /**2 * Generate Verification code3 * Transform the way to generate verification code, the picture Base64 form to the foreground, rather than directly pass the verification code to the front desk4      * @return5      * @throwsIOException6      */7      Public voidImagecode ()throwsIOException {8HttpServletResponse resp =commandcontext.getresponse ();9HttpServletRequest req =commandcontext.getrequest ();TenString method=Req.getmethod (); One         if("Options". Equals (method)) { A             return ; -         } -Map map=NewHashMap (); the  -         //Create an image in memory -         intwidth = +, height = 38; -BufferedImage image =Newbufferedimage (width, height, + Bufferedimage.type_int_rgb); -         //Get the graphics context +Graphics g =image.getgraphics (); A         //Generating Random classes atRandom random =NewRandom (); -         //Set Background color -G.setcolor (Getrandcolor (230, 255)); -G.fillrect (0, 0, 100, 40); -         //Set Font -G.setfont (NewFont ("Arial", Font.center_baseline | Font.Italic, 20)); in         //generates 0 lines of interference, -G.drawline (0, 0, 0, 0); to  +         //Store Verification Code -StringBuffer SRand =NewStringBuffer (); the          for(inti = 0; i < charcount; i++) { *String Singlecode =string.valueof (Codesequence[random.nextint (codesequence.length)); $ srand.append (singlecode);Panax Notoginseng             //Display the authentication code to the image -G.setcolor (Getrandcolor (100, 150));//The call function comes out with the same color, possibly because the seed is too close, so it can only be generated directly theg.DrawString (Singlecode, + * i + 5, 25); +         } A          for(inti=0;i< (Random.nextint (5) +5); i++){ theG.setcolor (NewColor (Random.nextint (255) +1,random.nextint (255) +1,random.nextint (255) +1)); +G.drawline (Random.nextint), Random.nextint (+), Random.nextint (+), Random.nextint (40)); -G.drawline (Random.nextint), Random.nextint (+), Random.nextint (+), Random.nextint (40)); $         } $  -HttpSession session =req.getsession (); -         //Get ClientID theString clientid=Systemutil.getclientid (req); -         if(Stringutils.isempty (clientId)) {Wuyi             //Generate ClientID theString Useragent=req.getheader ("User-agent"); -String sessionid=Session.getid (); WuString cip=Ippolicy.getclientip (req); -Clientid=Codeutil.genclientid (sessionid,cip,useragent); About         } $Map.put ("ClientId", clientId); -         if(isvalidatecodecasesensitive) { -Session.setattribute ("Randomcode", srand.tostring ()); - Systemutil.push2cache (ClientId, srand.tostring ()); A}Else { +Session.setattribute ("Randomcode", Srand.tostring (). toLowerCase ()); the Systemutil.push2cache (ClientId, Srand.tostring (). toLowerCase ()); -         } $         //Image Effective the g.dispose (); the         Try{ the  theBytearrayoutputstream OutputStream =NewBytearrayoutputstream (); -Imageio.write (image, "JPG", outputstream); inBase64encoder encoder =NewBase64encoder (); theString base64img =Encoder.encode (Outputstream.tobytearray ()); theBase64img= "Data:image/jpg;base64," +base64img.replaceall ("\ n", ""). ReplaceAll ("\ R", "");//delete \ r \ n; AboutMap.put ("Vercode", base64img); theObject jsonobj =Jsonserializer.tojson (map); the             byte[] json = jsonobj.tostring (). GetBytes ("UTF-8"); theResp.setcontenttype ("Text/plain;chartset=utf-8"); +Resp.setheader ("Cache-control", "No-cache"); -Resp.setheader ("Expires", "0"); theResp.setintheader ("Content-length", json.length);BayiServletoutputstream Responseoutputstream =Resp.getoutputstream (); the Responseoutputstream.write (JSON); the             //The following closes the input stream!  - Responseoutputstream.flush (); - responseoutputstream.close (); the             //Get page Key value the             return ; the}Catch(IOException e) { theLogger.error ("Production Verification Code Error", e); -             Throw NewSystemException ("Production Verification Code Error", e); the         } the     } the 94  the     /** the * get random colors for a given range the      *98      * @paramFC About      * @paramBC -      * @return101      */102Color Getrandcolor (intFcintBC) {103Random random =NewRandom ();104         if(FC > 255) theFC = 255;106         if(BC > 255)107BC = 255;108         intr = FC + random.nextint (BC-FC);109         intg = FC + random.nextint (BC-FC); the         intB = fc + random.nextint (BC-FC);111         return NewColor (R, G, b); the}

Java Generate CAPTCHA Code

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.