Verification Code Picture Generation step
Creates a BufferedImage object.
Gets the BufferedImage brush, which calls the Getgraphics () method to get the graphics object.
Call the Graphics object's SetColor () method and the FillRect () method to set the picture background color.
Call the Graphics object's SetColor () method and the DrawLine () method to set the picture noise line.
Call the Setrgb () method of the Bufferedimaged object to set the noise of the picture.
Call the Graphics object's SetColor () method, the SetFont () method, and the drawstring () method to set the picture verification code.
Because the image width and height of the verification code is determined according to the style of the website, the size of the font needs to be determined according to the width and height of the picture, with a little skill.
Package util;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.Image;
Import Java.awt.image.BufferedImage;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.util.Random;
Import Javax.imageio.ImageIO; public class Verification {private static final String alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
1234567890 "; /** * Generates a width for the width, height for height, captcha code for the picture * @param width of the picture @param height * @param code Verification Code String * @r Eturn return Picture Verification code */public static bufferedimage getImage (int width, int height, String code) {Returns GetImage (width,
Height, code, 20); /** * Generates a wide-width, high height, captcha code for the picture, the image of the interference line in the number of linecnt * @param width of the picture of the wide * @param height of the picture * @par Am code Verification Code String * @param the number of linecnt interference line, recommended 10, can be adjusted according to the results of the * @return return picture Verification code/public static BufferedImage Geti Mage (int width, int height, String code, int linecnt) {return createimage (WIDTH, height, code, linecnt, 0.01);
/** * Generates a width for the width, high for the height, verification code for the Code of the picture, the number of interference lines in the picture linecnt * Noise ratio is noiserate, that is, the percentage of noise pixels in the picture * @param width of the picture * @param height picture of the high * @param code Verification Code String * @param linecnt interference line number of bars, recommended to be about 10, can be adjusted according to the results of the * @param noiserate picture noise like Percentage of total pixels * @return return Picture Verification code */public static bufferedimage getImage (int width, int height, String code, int Linec
NT, double noiserate {return createimage (width, height, code, linecnt, noiserate); /** * * Generates a width for the width, high height, verification code for the picture, the number of disturbing lines in the picture is linecnt * Noise ratio is noiserate, that is, the percentage of noise pixels in the picture * @param wi DTH picture of the width * @param height of the picture of the high * @param code Verification Code String * @param linecnt Interference line number of the proposed 10, can be adjusted according to the results of the appropriate * @param Noisera Percentage of noise pixels in the te picture in total pixels * @return return Picture Verification code */private static bufferedimage createimage (int width, int height, String Co
DE, int linecnt, double noiserate) {int fontwidth = (int) (width * 0.8))/Code.length ();
int fontheight = (int) (height * 0.7); //in order to generate a good verification code at any width and height, the size of the font is small in Fontwdith ho fontheight, int fontsize = Math.min (Fontwidth, fontheight);
DrawString to use int paddingx = (int) (width * 0.1);
int paddingy = height-(height-fontsize)/2;
Create image BufferedImage buffimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);
Get the brush Graphics g = buffimg.getgraphics ();
Sets the color of the Brush G.setcolor (Getrandcolor (200, 255));
Then fill in a rectangle, which sets the background color g.fillrect (0, 0, width, height);
Set the noise line for (int i = 0; i < linecnt i++) {//Random get the start and end of the interference line int xs = (int) (Math.random () * width);
int ys = (int) (Math.random () * height);
int XE = (int) (Math.random () * width);
int ye = (int) (Math.random () * height);
G.setcolor (Getrandcolor (1, 255));
G.drawline (XS, Ys, Xe, ye);
//Add noise int area = (int) (noiserate * width * height);
for (int i=0; i<area; ++i) {int x = (int) (Math.random () * width); int y = (int) (Math.random () * height);
Buffimg.setrgb (x, y, (int) (Math.random () * 255));
}//Set fonts font font = new Font ("Ravie", Font.plain, FontSize);
G.setfont (font);
for (int i=0; i<code.length (); ++i) {String ch = code.substring (i, i+1);
G.setcolor (Getrandcolor (1, 199));
g.DrawString (CH, paddingx + fontwidth * I, paddingy);
return buffimg; /** * Gets a random color, r,g,b the value between L and R * @param l left interval * @param r right interval * @return return random color value * * private static color
Getrandcolor (int L, int R) {if (L > 255) L = 255;
if (R > 255) r = 255;
if (L < 0) L = 0;
if (r < 0) R = 0;
int interval = r-l;
int r = L + (int) (Math.random () * interval);
int g = L + (int) (Math.random () * interval);
int B = L + (int) (Math.random () * interval);
return new Color (R, G, b); /** * Randomly generated several strings composed of uppercase and lowercase letters and numbers * @param len randomly generates LEN characters * @return returns several randomly generated sizeA literal string of letters */public static string Getrandcode (int len) {String code = "";
for (int i=0; i<len; ++i) {int index = (int) (Math.random () * alphabet.length ());
Code = code + alphabet.charat (index);
} return code; /** * Convert picture to byte array * @param image Image * @return return byte array * @throws IOException/public static byte[]
Getbytearray (bufferedimage image) throws ioexception{bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
Imageio.write (Image, "png", BAOs);
return Baos.tobytearray ();
Bytearrayoutputstream does not require close}}
Use Captcha picture
In Verificationcode.java this servlet invokes the above class to generate the Captcha picture, and then returns the picture to the client.
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException C2/>httpsession session = Request.getsession ();
Randomly generates a string and writes the session
string code = Verification.getrandcode (4);
Session.setattribute ("Verification", code);
BufferedImage image = Util. Verification.getimage (100,30, Code, 5);
Response.setcontenttype ("Image/png");
OutputStream out = Response.getoutputstream ();
Out.write (util. Verification.getbytearray (image));
Out.flush ();
Out.close ();
}
Set up the authentication code in index.jsp, when the user clicks the authentication code, calls the JS code to request the server to obtain the new authentication code. Because the above-generated servlet will be cached by the browser, a random parameter should be given to the servlet in the JS code, so that the browser will send a request to the server for a new captcha instead of reading it in the cache.
<% @page import= "util. Verification "%> <%@ page language=" java "contenttype=" text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Finally, in Checkverification.java this servlet to determine whether the user entered the validation code is correct, in order to facilitate the user, the verification code is generally set to case insensitive, so first converted to lowercase letters and then compare.
protected void doget (HttpServletRequest request, httpservletresponse response) throws S
Ervletexception, IOException {HttpSession session = Request.getsession ();
String verification = (string) Session.getattribute ("Verification");
String submitverification = Request.getparameter ("submitverification");
PrintWriter out = Response.getwriter (); if (verification!=null && submitverification!=null) {if (Verification.tolowercase (). Equals (
Submitverification.tolowercase ()) {OUT.PRINTLN ("Yes!!!");
} else{out.println ("no!!!");
} else{out.println ("no!!!"); Session.removeattribute ("verification");//Prevent users from repeating the form}/** * @see httpservlet#dopost (httpservletrequest request, HttpServletResponse response) */protected void DoPost (HttpServletRequest request, httpservletresponse response) throw
S servletexception, IOException {//TODO auto-generated Method stub doget (request, response); }
The final run of the effect diagram is as follows
The above is the entire content of this article, I hope to help you learn.