Java version Imitation QQ authentication Code style picture verification Code _java

Source: Internet
Author: User
Tags border color rand set background sin

This article for everyone to share the Java version imitation QQ code style image Verification code, the specific contents are as follows

Features include: Custom picture size and character length, random background color and character color, random character offset angle, character smoothing edge, interference line, noise point, background distortion.
Originally want to do character twist, do not know how to distort the text and then the error, first of all, I hope that a master can help fix it.
Need to explain the reason is a bit like QQ authentication code is because of this Algerian font, if the system does not need to install, Baidu Search font name can be downloaded to, lost System Fonts folder on the line.

Effect Chart:

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 serial
 
 Versionuid = 1L; public void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {res
  Ponse.setheader ("Pragma", "No-cache");
  Response.setheader ("Cache-control", "No-cache");
  Response.setdateheader ("Expires", 0);
   
  Response.setcontenttype ("Image/jpeg");
  Generates a random string verifycode = Verifycodeutils.generateverifycode (4);
  HttpSession session = Request.getsession (true);
  Session.setattribute ("Rand", Verifycode.tolowercase ());
  Generate picture int w = 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{//Use to Algerian fonts, the system does not need to install fonts, fonts only show uppercase, remove the 1,0,i,o several easily confused characters public static final String VER
 Ify_codes = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
 
 
 private static Random Random = new Random (); /** * Use system default character mnemonic to generate CAPTCHA * @param verifysize Authenticode length * @return/public static String generateverifycode (int verifysiz
 e) {return Generateverifycode (verifysize, verify_codes); /** * Use the specified source to generate the verification code * @param verifysize Verification Code length * @param sources Verify code word mnemonic * @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 (int i = 0; i < verifysize i++) {verifycode.append (Sources.charat (Rand.nextint (codesLen-1)));
 return verifycode.tostring (); /** * Generates a random CAPTCHA file and returns a verification code value * @param w * @param h * @param outputfile * @param verifysize * @return * @thr OWS IOException */public static String outputverifyimage (int w, int h, File outputfile, int verifysize) throws Ioexcep
  tion{String Verifycode = Generateverifycode (verifysize);
  Outputimage (W, H, OutputFile, Verifycode);
 return verifycode; /** * Outputs random captcha picture streams and returns the verification code value * @param w * @param h * @param os * @param verifysize * @return * @throws IOE Xception */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; /** * Generates the specified CAPTCHA image file * @param w * @param h * @param outputfile * @param code * @throws IOException/PU
   Blic 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 specified CAPTCHA picture stream * @param w * @param h * @param OS * @param code * @throws IOException/Public s
  tatic 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.yellow};
  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 Border color g2.fillrect (0, 0, W, h);
  Color C = Getrandcolor (200, 250);
   
  G2.setcolor (c)//Set background color g2.fillrect (0, 2, W, h-4);
  Draw interference line Random Random = new Random ();
   G2.setcolor (Getrandcolor (160, 200));//Set the color of the line for (int i = 0; i < 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 +, Y + yl + 20);
  ///Add noise point 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 = Getrandomintcolor ();
  Image.setrgb (x, y, RGB);
  Shear (G2, W, H, c);//make the picture distorted 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 < H1 i++) {double d = (double) (period >> 1) * Math.sin (double) I/(double) period + (6.2831853071795862D * (double) phase)/(double) frames);
   G.copyarea (0, I, W1, 1, (int) d, 0);
    if (bordergap) {g.setcolor (color);
    G.drawline ((int) d, I, 0, i);
   G.drawline ((int) d + W1, I, W1, i); }} private static void Sheary (Graphics g, int W1, int h1, color color) {int period = Random.nextint (40) + 10;
 
  50;
  Boolean bordergap = true;
  int frames = 20;
  int phase = 7;
       for (int i = 0; i < W1 i++) {Double d = (double) (period >> 1) * Math.sin (double) I/(double) period
   + (6.2831853071795862D * (double) phase)/(double) frames);
   G.copyarea (i, 0, 1, H1, 0, (int) d);
    if (bordergap) {g.setcolor (color);
    G.drawline (i, (int) d, I, 0);
   G.drawline (i, (int) d + H1, I, H1);
  }} public static void Main (string[] args) throws ioexception{file dir = new file ("F:/verifies");
  int w =, h = 80;
   for (int i = 0; i < i++) {String Verifycode = Generateverifycode (4); File filE = new File (dir, Verifycode + ". jpg");
  Outputimage (W, h, file, Verifycode);
 }
 }
}

Web.xml configuration:

  <servlet>
   <servlet-name>AuthImage</servlet-name>
   <servlet-class> hh.com.util.authimage</servlet-class>
  </servlet>
  <servlet-mapping>
   < servlet-name>authimage</servlet-name>
  <url-pattern>/authImage</url-pattern>
  </ Servlet-mapping>

The above is the entire content of this article, I hope to be able to learn Java image Verification code inspiration.

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.