ValidateCode.java verification code generation class
package cn.dsna.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 * @author dsna * */ public class ValidateCode { // The width of the image. private int width = 160; // The height of the image. private int height = 40; // number of verification code characters private int codeCount = 5; // Number of verification code interference lines private int lineCount = 150; // verification code private String code = null; // verification code image 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 image width * @param height image height */ public ValidateCode(int width,int height) { this.width=width; this.height=height; this.createCode(); } /** * * @param width image width * @param height image height * @param codeCount number of 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 - 2;//The height of the 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); // create font 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 records the randomly generated verification code StringBuffer randomCode = new StringBuffer(); // Randomly generate a verification code of codeCount characters. for (int i = 0; i < codeCount; i++) { String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); // Generate random color values, so that the color value of each character 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); // Combine the four random numbers generated. 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 String getCode() { return code; } }
ImgFontByte.java
package cn.dsna.util.images; import java.io.ByteArrayInputStream; import java.awt.*; /** * ttf font file * @author dsna * */ public class ImgFontByte { public Font getFont(int fontHeight){ try { Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(hex2byte(getFontByteStr()))); return baseFont.deriveFont(Font.PLAIN, fontHeight); } catch (Exception e) { return new Font("Arial",Font.PLAIN, fontHeight); } } private byte[] hex2byte(String str) { if (str == null) return null; str = str.trim (); int len = str.length(); if (only == 0 || only% 2 == 1) return null; byte [] b = new byte [len / 2]; try { for (int i = 0; i < str.length(); i += 2) { b[i / 2] = (byte) Integer .decode("0x" + str.substring(i, i + 2)).intValue(); } return b; } catch (Exception e) { return null; } } /** * Hex string of ttf font file * @return */ private String getFontByteStr(){ return null; return str;//The string is too long to find in the attachment } }
ValidateCodeServlet.java Servlet calling method
package cn.dsna.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; @Override protected void doGet(HttpServletRequest reqeust, HttpServletResponse response) throws ServletException, IOException { // Set the type format of the response to image format response.setContentType("image/jpeg"); // Disable image caching. response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); HttpSession session = reqeust.getSession(); ValidateCode vCode = new ValidateCode(120,40,5,100); session.setAttribute("code", vCode.getCode()); vCode.write(response.getOutputStream()); } /** * web.xml add servlet <servlet> <servlet-name>validateCodeServlet</servlet-name> <servlet-class>cn.dsna.util.images.ValidateCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>validateCodeServlet</servlet-name> <url-pattern>*.images</url-pattern> </servlet-mapping> Type XXX/dsna.images in the address bar to test */ }
test class
ValidateCodeTest.java
package cn.dsna.util.images; import java.io.IOException; import java.util.Date; public class ValidateCodeTest { /** * @param args */ public static void main(String[] args) { ValidateCode vCode = new ValidateCode(120,40,5,100); try { String path="D:/t/"+new Date().getTime()+".png"; System.out.println(vCode.getCode()+" >"+path); vCode.write(path); } catch (IOException e) { e.printStackTrace (); } } }
web.xml configuration
<servlet> <servlet-name>validateCodeServlet</servlet-name> <servlet-class>cn.dsna.util.images.ValidateCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>validateCodeServlet</servlet-name> <url-pattern>*.images</url-pattern> </servlet-mapping>