Java Graphics Verification Code generation tool class and Web page checksum verification code __web

Source: Internet
Author: User
Tags stringbuffer

Recently to use graphics verification code, the Internet to find information, reference changed a tool class, and added to the program, the following recorded to do the backup, the main reference to http://www.iteye.com/topic/573456 article changes, added comments, and Web page checksum verification code

Package Com.jd.jr.faecms.common.validateCode;
Import Javax.imageio.ImageIO;
Import java.awt.*;
Import Java.awt.image.BufferedImage;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.util.Date;

Import Java.util.Random;
    /** * Verification Code Generator * * @author/public class Validatecode {//Picture width.
    private int width = 160;
    The height of the picture.
    private int height = 40;
    Number of authentication code characters private int codecount = 5;
    Verification code Interference line number private int linecount = 150;
    Authentication code private String code = NULL;

    Verify code picture buffer private BufferedImage buffimg = null; Verification code range, remove 0 (digits) and O (Pinyin) easily confused (lowercase 1 and L can also be removed, capital not used) Private char[] Codesequence = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 1 ', ' 2 ', ' 3 '

    , ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};
    /** * default constructor, set default parameter */public Validatecode () {this.createcode ();

 }   /** * @param width picture width * @param height picture high/public validatecode (int width, int height) {
        This.width = width;
        This.height = height;
    This.createcode (); /** * @param width picture width * @param height picture high * @param codecount number of characters * @param linecount interference
        Line number */public validatecode (int width, int height, int codecount, int linecount) {this.width = width;
        This.height = height;
        This.codecount = Codecount;
        This.linecount = LineCount;
    This.createcode ();
        public void Createcode () {int x = 0, fontheight = 0, Codey = 0;

        int red = 0, green = 0, blue = 0;

        x = width/(codecount + 2);//width of each character (one character left and right) Fontheight = height-2;//font height Codey = height-4;
        Image buffer buffimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);
        Graphics2D g = buffimg.creategraphics ();
        Generate random numbersRandom Random = new Random ();
        Fill the image with a white g.setcolor (color.white);
        G.fillrect (0, 0, width, height);
Create fonts that can be modified to other font font = new Font ("Fixedsys", Font.plain, Fontheight);
        Font font = new Font ("Times New Roman", Font.roman_baseline, Fontheight);

        G.setfont (font);
            for (int i = 0; i < LineCount; i++) {//Set random start and end coordinates int xs = random.nextint (width);//x coordinates start int ys = random.nextint (height);//y coordinates start int XE = xs + random.nextint (WIDTH/8);//x coordinate end I
            NT ye = ys + random.nextint (HEIGHT/8);//y coordinate ends//produces random color values, so that the color values of each of the output interference lines will be different.
            Red = random.nextint (255);
            Green = Random.nextint (255);
            Blue = Random.nextint (255);
            G.setcolor (New Color (red, green, blue));
        G.drawline (XS, Ys, Xe, ye);
        }///Randomcode records randomly generated verification code stringbuffer Randomcode = new StringBuffer (); Random generation of CodecoUnt a character's captcha. for (int i = 0; i < Codecount i++) {String Strrand = string.valueof Codesequence[random.nextint (codeseque
            Nce.length)]);
            Produces a random color value that gives the output a different color value for each character.
            Red = random.nextint (255);
            Green = Random.nextint (255);
            Blue = Random.nextint (255);
            G.setcolor (New Color (red, green, blue));
            g.DrawString (Strrand, (i + 1) * x, Codey);
            The resulting four random numbers are grouped together.
        Randomcode.append (Strrand);
        ///Save the four-digit CAPTCHA to the session.
    Code = randomcode.tostring ();
        public void Write (String path) throws IOException {outputstream SOS = new FileOutputStream (path);
    This.write (SOS);
        public void Write (OutputStream sos) throws IOException {Imageio.write (buffimg, "PNG", SOS);
    Sos.close ();
    Public BufferedImage getbuffimg () {return buffimg;
    Public String GetCode () {return code;
 }

    /**    * Test function, default generation to D disk * @param args/public static void main (string[] args) {Validatecode Vcode = NE
        W Validatecode (160,40,5,150);
            The try {String path= "d:/" +new Date (). GetTime () + ". png";
            System.out.println (Vcode.getcode () + ">" +path);
        Vcode.write (path);
        catch (IOException e) {e.printstacktrace ();
 }
    }
}

The following is a page call validation code

<div class= "Form-group  col-lg-6" >     <label for= "id" class= "col-sm-4 Control-label" >         Verification code:     </label>     <div class= "col-sm-8" >     &NB Sp   <input type= "text" id= "code" name= "code" class= "Form-control" style= "width:250px"; />          nbsp       <a href= "#" onclick= "changeimg ()" > for one </a>     </div> </div> <s
        Cript type= "Text/javascript" >//Refresh Picture function changeimg () {var imgsrc = $ ("#imgObj");
        var src = imgsrc.attr ("src");
    Imgsrc.attr ("src", Changeurl (SRC));
        }//In order to make the picture inconsistent each time, that is, the browser does not read the cache, so you need to add timestamp function Changeurl (URL) {var timestamp = (new Date ()). valueof ();
        var index = Url.indexof ("?", url); if (Index > 0) {url = url.substring (0, url.)IndexOf (URL, "?"));
        } if ((Url.indexof ("&") >= 0)) {url = url + "xtamp=" + timestamp;
        } else {url = url + "? timestamp=" + timestamp;
    } return URL; } </script>


Below is the controller layer output verification code

	/**
	 * Response Verification code page
	 * @return
	/@RequestMapping (value= "/validatecode") public
	String Validatecode ( HttpServletRequest request,httpservletresponse response) throws exception{
		//Set the type format of the response as Picture format
		Response.setcontenttype ("Image/jpeg");
		Disables image caching.
		Response.setheader ("Pragma", "No-cache");
		Response.setheader ("Cache-control", "No-cache");
		Response.setdateheader ("Expires", 0);

		HttpSession session = Request.getsession ();

		Validatecode Vcode = new Validatecode (120,40,5,100);
		Session.setattribute ("Code", Vcode.getcode ());
		Vcode.write (Response.getoutputstream ());
		return null;
	}

The following is the controller layer verify that the validation code input is correct

		String code = request.getparameter ("code");
		HttpSession session = Request.getsession ();
		String sessioncode = (string) session.getattribute ("code");
		if (! Stringutils.equalsignorecase (Code, Sessioncode)) {  //Ignore Authenticode case
			throw new RuntimeException ("Verify code does not correspond to code=" + Code + "  sessioncode=" + sessioncode);
		}


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.