Java Picture Verification Code generation tutorial detailed _java

Source: Internet
Author: User

First of all, let's look at how to generate the local image verification code, and then write output to the Web page verification code how to achieve.

First look at the simplest-the function of the implementation is to write a string into a picture into a file

Implementation code:

Package cn.hncu.img;

Import Java.awt.Graphics;
Import Java.awt.image.BufferedImage;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import Javax.imageio.ImageIO;
This class contains some static and convenient methods for locating ImageReader and ImageWriter and performing simple coding and decoding.

import org.junit.Test;

public class Imgdemo {

 //Learn how to turn a string into a picture to write to a file
 @Test public
 void ImgDemo1 () throws FileNotFoundException, ioexception{
  bufferedimage img = new BufferedImage (A, BUFFEREDIMAGE.TYPE_INT_RGB);
  Represents an image that has a 8-bit RGB color component that synthesizes integer pixels.
  Graphics g = img.getgraphics ();
  g.DrawString ("Hello", 10,20);
  Draws the text given by the specified string using the current font and color of this graphics context. The baseline of the leftmost character is located at the (x, Y) position of the graphics context coordinate system.
  g.dispose ()////similar to the close () drive flush () in the stream---to brush the data into the IMG object
  //Release the graphics context and all the system resources it uses. After you call Dispose, you can no longer use the Graphics object. 
  imageio.write (IMG, "JPG", New FileOutputStream ("img/a.jpg"));
  Writes an image to File using an arbitrary imagewriter that supports the freeze-hold.
 }

}

Results:

The top one is very simple, right, we see the verification code is not like that, well, we give it some interference lines, background color, character and y coordinates randomly generated.

Captcha with interference line and background color-write to File

Demo Code:

Package cn.hncu.img;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.image.BufferedImage;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.util.Date;

Import Java.util.Random;
Import Javax.imageio.ImageIO;

This class contains some static and convenient methods for locating ImageReader and ImageWriter and performing simple coding and decoding.

Import Org.junit.Test; public class Imgdemo {//Convert the above string to our usual captcha---generate several random numbers, with background color and disturbing line @Test public void ImgDemo2 () throws Filenotfoundexcepti
  On, ioexception{int width = 80;
  int height= 40;
  int lines = 10;

  BufferedImage img = new BufferedImage (width, height, bufferedimage.type_int_rgb);

  Graphics g = img.getgraphics ();
  Set Background color g.setcolor (color.white); G.fillrect (0, 0, width, height);//Draw background//fill the specified rectangle.

  Fills the rectangle with the current color of the graphics context//sets the font G.setfont (new font ("Arial", Font.Bold, 18));
  Random number Date D = new Date ();
  System.out.println (D.gettime ());
  Random r = new Random (D.gettime ()); for (int i=0;i<4;i++){int a = R.nextint (10);//10 integer [0,9] int y = 10+r.nextint (20); An integer in//10~30 range, as y-coordinate color c = new Color (R.nex
   TInt (255), R.nextint (255), R.nextint (255));
   G.setcolor (c);
  g.DrawString ("" +a, 5+i*width/4, y);
   }//Interference line for (int i=0;i<lines;i++) {color c = new color (r.nextint (255), R.nextint (255), R.nextint (255));
   G.setcolor (c);
  G.drawline (R.nextint (width), r.nextint (height), r.nextint (width), r.nextint (height));

 G.dispose ()//close () is similar to the close () drive flush () in the stream---to brush the data into an IMG object Imageio.write (IMG, "JPG", New FileOutputStream ("img/b.jpg"));

 }


}

Demo results:

Finally, look at a code that can be rotated and indented-write to the picture local file

Demo Code:

Package cn.hncu.img;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.geom.AffineTransform;
Import Java.awt.image.BufferedImage;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.util.Date;

Import Java.util.Random;
Import Javax.imageio.ImageIO;

This class contains some static and convenient methods for locating ImageReader and ImageWriter and performing simple coding and decoding.

Import Org.junit.Test; public class Imgdemo {@Test//can rotate and shrink the authentication Code public void ImgDemo3 () throws FileNotFoundException, ioexception{int width
  = 80;
  int height = 40;
  int lines = 10;
  BufferedImage img = new BufferedImage (width, height, bufferedimage.type_int_rgb);

  Graphics2D g2d = (graphics2d) img.getgraphics ();


  G2d.setfont (New Font ("Song Body", Font.Bold, 20));

  Random r = new Random (new Date (). GetTime ());
  Sets the background color g2d.setcolor (new color (r.nextint (255), R.nextint (255), R.nextint (255));
  G2d.drawrect (0, 0, width, height);//Draw the border of the specified rectangle. G2d.setcoLor (New Color (R.nextint (255), R.nextint (255), R.nextint (255)));

  G2d.fillrect (0, 0, width, height);//fills the specified rectangle.

   for (int i=0;i<4;i++) {String str = "" +r.nextint (10);
   Handle rotation AffineTransform Tx = new AffineTransform ();
   Tx.rotate (Math.random (), 5+i*15, height-5);
   The angle of rotation measured in radians, the x-coordinate of the rotating anchor point, the Y-coordinate//tx.scale of the rotating anchor (0.7+math.random (), 0.7+math.random ());
   The scaling multiples of the X coordinate direction, the scaling multiples of the y-coordinate direction g2d.settransform (Tx);
   Color c = new color (r.nextint (255), R.nextint (255), R.nextint (255));
   G2d.setcolor (c);
  G2d.drawstring (str, 2+I*WIDTH/4, HEIGHT-13);
   }//Interference line for (int i=0;i<lines;i++) {color c = new color (r.nextint (255), R.nextint (255), R.nextint (255));
   G2d.setcolor (c);
  G2d.drawline (R.nextint (width), r.nextint (height), r.nextint (width), r.nextint (height));

  } g2d.dispose ();
 Imageio.write (IMG, "JPG", New FileOutputStream ("img/c.jpg"));

 }
}

Demo results:

The following is the beginning of the demo front of the image verification technology.

Picture verification technology at the front desk

Structure diagram of this project:

INDEX.JSP:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <!

DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

Xml:

 <?xml version= "1.0" encoding= "UTF-8"?> "<web-app version=" 3.0 "xmlns=" http://j Ava.sun.com/xml/ns/javaee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http:// Java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "> <display-name></ Display-name> <servlet> <description>this is the description a my Java EE component</description> &l T;display-name>this is, the display name of my Java EE component</display-name> <servlet-name>imageservlet& Lt;/servlet-name> <servlet-class>cn.hncu.img.ImageServlet</servlet-class> </servlet> < Servlet-mapping> <servlet-name>ImageServlet</servlet-name> <url-pattern>/servlet/ imageservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp </welcome-file> </welcome-file-list> </web-app> 

Imageservlet.java

Package cn.hncu.img;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.image.BufferedImage;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Date;

Import Java.util.Random;
Import Javax.imageio.ImageIO;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; public class Imageservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respon
 SE) throws Servletexception, IOException {doPost (request, response); 
  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {

  Tell the client that the output format response.setcontenttype ("Image/jpeg");
  int width = 80;
  int height = 40;
  int lines = 10;

  BufferedImage img = new BufferedImage (width, height, bufferedimage.type_int_rgb);

  Graphics g = img.getgraphics (); Set backgroundColor G.setcolor (color.white);

  G.fillrect (0, 0, width, height);

  Sets the font g.setfont (new font ("Arial", Font.Bold, 20));
  Random number Random R = new Random (new Date (). GetTime ());
   for (int i=0;i<4;i++) {int a = R.nextint (10);
   int y = 10+r.nextint (20); An integer in the range of//10~30, as y-coordinate color c = new color (r.nextint (255), R.nextint (255), R.nextint (255));

   G.setcolor (c);
  g.DrawString ("" +a, 5+i*width/4, y);
   }//Interference line for (int i=0;i<lines;i++) {color c = new color (r.nextint (255), R.nextint (255), R.nextint (255));
   G.setcolor (c);
  G.drawline (R.nextint (width), r.nextint (height), r.nextint (width), r.nextint (height));
 The G.dispose ()//close () is similar to the stream's close () drive flush ()---to brush the data into an IMG object Imageio.write (IMG, "JPG", Response.getoutputstream ());

 }

}

Demo results:

The following is in index.jsp:
If you are using this sentence:
img.src= "/myhelloweb/servlet/imageservlet";

You can look at the response head:

And look at the response head with this sentence:
img.src= "/myhelloweb/servlet/imageservlet?" +time;

One more date response!
Because the time is changing, so each point can not see clearly, will again request to the server, and not because of the browser's cache, and not to request.

The verification code is over here first.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.