JAVA image verification code and java Verification Code

Source: Internet
Author: User

JAVA image verification code and java Verification Code

Package hh.com. util; import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; public class AuthImage extends javax. servlet. http. httpServlet implements javax. servlet. servlet {static final long serialVersionUID = 1L; public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setHeader ("Pragma", "No-cache"); response. setHeader ("Cache-Control", "no-cache"); response. setDateHeader ("Expires", 0); response. setContentType ("image/jpeg"); // generates the random String verifyCode = VerifyCodeUtils. generateVerifyCode (4); // Save the session sessionHttpSession session = request. getSession (true); session. setAttribute ("rand", verifyCode. toLowerCase (); // generate an image int w = 200, h = 80; VerifyCodeUtils. outputImage (w, h, response. getOutputStream (), verifyCode );}}

VerifyCodeUtils class

Package hh.com. util; import java. awt. color; import java. awt. font; import java. awt. graphics; import java. awt. graphics2D; import java. awt. linearGradientPaint; import java. awt. paint; import java. awt. renderingHints; import java. awt. geom. affineTransform; import java. awt. image. bufferedImage; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStream; import java. util. Arrays; import java. util. random; import javax. imageio. imageIO; public class VerifyCodeUtils {// The Algerian font is used. If the font is not in the system, the font needs to be installed. Only uppercase letters are displayed, with, I removed, o several confusing characters: public static final String VERIFY_CODES = "23456789 ABCDEFGHJKLMNPQRSTUVWXYZ"; private static Random random = new Random (); /*** use the system default character source to generate a Verification Code * @ param verifySize the verification code length * @ return */public static String generateVerifyCode (int verifySize) {return generateVeri FyCode (verifySize, VERIFY_CODES );} /*** use the specified source to generate a Verification Code * @ param verifySize verification code length * @ param sources Verification Code character source * @ return */public static String generateVerifyCode (int verifySize, String sources) {if (sources = null | sources. length () = 0) {sources = VERIFY_CODES;} int codesLen = sources. length (); Random rand = new Random (System. currentTimeMillis (); StringBuilder verifyCode = new StringBuilder (verifySize); for (in T I = 0; I <verifySize; I ++) {verifyCode. append (sources. charAt (rand. nextInt (codesLen-1);} return verifyCode. toString ();}/*** generate a Random verification code file, return the verification code value * @ param w * @ param h * @ param outputFile * @ param verifySize * @ return * @ throws IOException */public static String outputVerifyImage (int w, int h, file outputFile, int verifySize) throws IOException {String verifyCode = generateVerifyCode (verifySize); out PutImage (w, h, outputFile, verifyCode); return verifyCode;}/*** outputs the Random verification code image stream, return the verification code value * @ param w * @ param h * @ param OS * @ param verifySize * @ return * @ throws IOException */public static String outputVerifyImage (int w, int h, outputStream OS, int verifySize) throws IOException {String verifyCode = generateVerifyCode (verifySize); outputImage (w, h, OS, verifyCode); return verifyCode ;} /*** generate the image file of the specified Verification Code * @ Param w * @ param h * @ param outputFile * @ param code * @ throws IOException */public static void outputImage (int w, int h, File outputFile, String code) throws IOException {if (outputFile = null) {return;} File dir = outputFile. getParentFile (); if (! Dir. exists () {dir. mkdirs ();} try {outputFile. createNewFile (); FileOutputStream fos = new FileOutputStream (outputFile); outputImage (w, h, fos, code); fos. close () ;}catch (IOException e) {throw e ;}} /*** output the specified Verification code image stream * @ param w * @ param h * @ param OS * @ param code * @ throws IOException */public static void outputImage (int w, int h, OutputStream OS, String code) throws IOException {int verifySize = code. length (); BufferedImage image = new BufferedImage (w, h, BufferedImage. TYPE_INT_RGB); Random rand = new Random (); Graphics2D g2 = image. createGraphics (); g2.setRenderingHint (RenderingHints. KEY_ANTIALIASING, RenderingHints. VALUE_ANTIALIAS_ON); Color [] colors = new Color [5]; Color [] colorSpaces = new Color [] {Color. WHITE, Color. CYAN, Color. GRAY, Color. LIGHT_GRAY, Color. MAGENTA, Color. ORANGE, Color. PINK, Color. YELLO W}; float [] fractions = new float [colors. length]; for (int I = 0; I <colors. length; I ++) {colors [I] = colorSpaces [rand. nextInt (colorSpaces. length)]; fractions [I] = rand. nextFloat ();} Arrays. sort (fractions); g2.setColor (Color. GRAY); // set the border Color g2.fillRect (0, 0, w, h); Color c = getRandColor (200,250); g2.setColor (c); // set the background Color g2.fillRect (0, 2, w, H-4); // draw interference line Random random = new Random (); g2.setColor (getRandColor (160,200); // set the line color for (int I = 0; I <20; I ++) {int x = random. nextInt (w-1); int y = random. nextInt (h-1); int xl = random. nextInt (6) + 1; int yl = random. nextInt (12) + 1; g2.drawLine (x, y, x + xl + 40, y + yl + 20);} // Add the noise float yawpRate = 0.05f; // noise rate int area = (int) (yawpRate * w * h); for (int I = 0; I <area; I ++) {int x = random. nextInt (w); int y = random. nextInt (h); int rgb = getRandomIntCo Lor (); image. setRGB (x, y, rgb);} shear (g2, w, h, c); // twist the image g2.setColor (getRandColor (100,160); int fontSize = H-4; font font = new Font ("Algerian", Font. ITALIC, fontSize); g2.setFont (font); char [] chars = code. toCharArray (); for (int I = 0; I <verifySize; I ++) {AffineTransform affine = new AffineTransform (); affine. setToRotation (Math. PI/4 * rand. nextDouble () * (rand. nextBoolean ()? 1:-1), (w/verifySize) * I + fontSize/2, h/2); g2.setTransform (affine); g2.drawChars (chars, I, 1, (w-10) /verifySize) * I + 5, h/2 + fontSize/2-10);} g2.dispose (); ImageIO. write (image, "jpg", OS);} private static Color getRandColor (int fc, int bc) {if (fc> 255) fc = 255; if (bc> 255) bc = 255; int r = fc + random. nextInt (bc-fc); int g = fc + random. nextInt (bc-fc); int B = fc + random. nextInt (bc-fc); return new Color (r, g, B);} private static int getRandomIntColor () {int [] rgb = getRandomRgb (); int color = 0; for (int c: rgb) {color = color <8; color = color | c;} return color;} private static int [] getRandomRgb () {int [] rgb = new int [3]; for (int I = 0; I <3; I ++) {rgb [I] = random. nextInt (255);} return rgb;} private static void shear (Graphics g, int w1, int h1, Color color) {shearX (g, w1, h1, color ); shearY (g, w1, h1, color);} private static void shearX (Graphics g, int w1, int h1, Color color) {int period = random. nextInt (2); boolean borderGap = true; int frames = 1; int phase = random. nextInt (2); for (int I = 0; I 

Web. xml configuration:

1     <servlet>2         <servlet-name>AuthImage</servlet-name>3         <servlet-class>hh.com.util.AuthImage</servlet-class>4       </servlet>5       <servlet-mapping>6         <servlet-name>AuthImage</servlet-name>7         <url-pattern>/authImage</url-pattern>8       </servlet-mapping>

 

Related Article

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.