Java code Generation image Verification Code implementation

Source: Internet
Author: User

Introducing an example of using Java code to generate a random picture verification code

Java code randomly generated image verification code

Package com.rchm.util.images;


Import Java.awt.Color;


Import Java.awt.Font;
Import Java.awt.Graphics2D;
Import Java.awt.image.BufferedImage;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.util.Random;


Import Javax.imageio.ImageIO;


/**
* Verification Code generator
*/
public class Validatecode {

The width of the picture.
private int width = 160;
The height of the picture.
private int height = 40;
Number of verification code characters
private int codecount = 5;
Number of interference lines for verification code
private int linecount = 150;
Verification Code
private static String code = NULL;
Verification Code Picture Buffer
Private BufferedImage Buffimg=null;


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 '};


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 number of Codecount characters
* @param linecount number of interference lines
*/
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
Fontheight = height of height-2;//font
Codey = height-4;

Image buffer
buffimg = new BufferedImage (width, height,bufferedimage.type_int_rgb);
Graphics2D g = buffimg.creategraphics ();
Generate random numbers
Random random = new random ();
Fill the image with white
G.setcolor (Color.White);
G.fillrect (0, 0, width, height);
Creating fonts
Imgfontbyte imgfont=new imgfontbyte ();
Font font =imgfont.getfont (fontheight);
G.setfont (font);

for (int i = 0; i < LineCount; i++) {
int xs = random.nextint (width);
int ys = random.nextint (height);
int XE = Xs+random.nextint (WIDTH/8);
int ye = Ys+random.nextint (HEIGHT/8);
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 recording of randomly generated verification codes
StringBuffer Randomcode = new StringBuffer ();
Randomly generates a Codecount character verification code.
for (int i = 0; i < Codecount; i++) {
String Strrand = string.valueof (Codesequence[random.nextint (codesequence.length)]);
Produces a random color value so that the color values for each character of the output will be different.
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 verification code 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 static String GetCode () {
return code;
}

}

Use this class in a servlet:

Package com.rchm.util.images;


Import java.io.IOException;


Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;


public class Validatecodeservlet extends HttpServlet {

Private static final long serialversionuid = 1L;


protected void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {
Response.setcontenttype ("Image/jpeg");
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
Validatecode Vcode = new Validatecode (100,30,4,100);
HttpSession session = Request.getsession ();
Session.removeattribute ("Validatecode");
Vcode.write (Response.getoutputstream ());
Session.setattribute ("Validatecode", Vcode.getcode ());
Vcode.write (Response.getoutputstream ());
}

}

Configure the servlet access path in Web. xml:

<servlet>
<servlet-name>validateCodeServlet</servlet-name>
<servlet-class>com.rchm.util.images.ValidateCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validateCodeServlet</servlet-name>
<url-pattern>code.images</url-pattern>

Java code Generation image Verification Code implementation

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.