Easy to learn the generation of verification codes in Web pages (JAVA)

Source: Internet
Author: User
Tags set background

The basic process of validating code generation1. Verification code generation, we can see the graphics object is drawn out. Object we have to get the Graphics object
1-1,Graphicsacquisition of objects, to be obtained through BufferedImage
<span style= "FONT-SIZE:18PX;" >int width=100;//determines the size of the box int height=40; BufferedImage BFI =new bufferedimage (width, height, bufferedimage.type_int_rgb); Graphics G=bfi.getgraphics ();//Graphics object can draw </span>



1-2, general Verification Code background box is white
<span style= "FONT-SIZE:18PX;" >//1, set background (white box) G.setcolor (color.white);//White Brush g.fillrect (0, 0, Width, height)//Rectangle Rectangle Frame </span>


1-3, save data (background verification used) and set font style (beautiful)
String str= "";//Save Data Random rom=new random ();//Set the uppercase and coarse g.setfont of the font (new font ("a", font.bold,20);
1-4. Generate specific values, and randomly generated colors
for (int i=0;i<4;i++) {int num=rom.nextint (10);//generated random number G.setcolor (new Color (Rom.nextint), Rom.nextint (256), Rom.nextint (256)));//Set the color of the brush (random) g.drawstring ("" +num, 20*i, 20+rom.nextint (10));//Draw the line, x position each increment 20,y coordinates to 201 lines, Online or Offline//ps: The location needs to be clear,}
1-5. The general number is easily recognized by other software, in order to prevent black. Add a little bit of interference to the line
Draw some interference lines for (int i = 0; i < i++) {G.setcolor (new Color (Rom.nextint), Rom.nextint (n), Rom.nextint (256));//Set The color of the brush (random) G.drawline (rom.nextint), Rom.nextint (+), Rom.nextint (+), Rom.nextint (40));//position is also random, x, y value do not exceed the rectangle box}
1-6. Destructiongraphics objects and storing pictures
<span style= "White-space:pre" ></span>g.dispose ();//Destroy Object Imageio.write (BFI, "JPEG", Res.getoutputstream ());//Picture with a byte stream directly get PS::  : Res is inside the servlet.
So the verification code is generated, then how do we import to the front desk?
2,Specific implementationforeground Code rendering ():
<body>    
The source of the SRC address is sent from the background. The path is very interesting. 2-1 stepsproject inside myeclipse--src-->new The Servlet appears as follows:

Click----next to appear on the following page:


This configuration is automatically included in the Web-inf folder inside the project, Web. Xml. The value inside this box is the path that needs to be accessed in the foreground src,----> click Finish. it's automatic. Generate the following interface:
You can write the previous code here. However, it is important to note that we must override this method to be effective:
protected void Service (HttpServletRequest req, HttpServletResponse resp)//auto-Generate input <span style= "font-family:arial, Helvetica, Sans-serif; " >service  complete, auto-generate </span>throws servletexception, IOException {//TODO auto-generated method Stubsuper.service (req, resp);}
The specific code is as follows:
Package Cn.hncu.com.servlet;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import Java.awt.image.bufferedimage;import Java.io.fileoutputstream;import Java.io.ioexception;import java.util.Random; Import Javax.imageio.imageio;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.servletresponse;import Javax.servlet.http.httpservlet;import Javax.servlet.http.HttpServletRequest Import Javax.servlet.http.httpservletresponse;public class Imgdemo extends HttpServlet {@Overridepublic void service ( ServletRequest req, servletresponse Res) throws Servletexception, IOException {int width=100;//determines the size of the box int height=40; BufferedImage BFI =new bufferedimage (width, height, bufferedimage.type_int_rgb); Graphics G=bfi.getgraphics ();//Get the Graphics object can draw//1, set the background (white box) G.setcolor (color.white);//White Brush g.fillrect (0, 0, width, height),//Draw Rectangle Rectangle box//2, generate random number string str= "";//Save Data Random rom=new random ();//Set the uppercase and coarse g.setfont of the font (the new font ("a", font.bold,20));//Draw a specific picture for(int i=0;i<4;i++) {int Num=rom.nextint (10);//generated random number G.setcolor (new Color (Rom.nextint, Rom.nextint (n), Rom.nextint (256)));// Set the color of the brush (random) g.drawstring ("" +num, 20*i, 20+rom.nextint (10));//Draw the line, x position each increment 20,y coordinates to 201 lines, online or offline//ps: Position needs to be clear,}// Draw some interference lines for (int i = 0; i < i++) {G.setcolor (new Color (Rom.nextint), Rom.nextint (n), Rom.nextint (256));//Set Brush The color (random) g.drawline (rom.nextint), Rom.nextint (+), Rom.nextint (+), Rom.nextint (40));//position is also random, x, y value do not exceed the rectangle box} G.dispose (); Imageio.write (BFI, "JPEG", Res.getoutputstream ());//Picture with byte stream directly get}}<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " ></span>
Front Code:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >For the foreground code, you need to explain:when our verification code sent over to see the need to refresh, and the browser has the function of automatic memory, when no new parameters passed in, the browser will not be refreshed, so we need to manually write a JS control parameters, we know, only the time will not change,  All of us take the time to pass as parameters. PS: Self-pit for a period of time problem: Verification code path problem.  The front-end "/" represents the Tomcat directory, which is represented within the project, such as "/" in Web. Xml. In other words, the two of them are in a bad directory.

At the end of the test, I attach the code and change the shape of the number of questions, such as the effect of changing to a more beautiful. Have a very clear record.
Package Cn.hncu.com;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.random;import Javax.imageio.ImageIO; Import Org.junit.test;public class Demoimg {@Testpublic void Test () throws exception{string str= "9988"; int width=60;int h eight=30;//BufferedImage object to get the Graphics object BufferedImage bfi=new bufferedimage (width, height, bufferedimage.type_int_ BGR); Graphics g=bfi.getgraphics (); g.drawstring (str, 10,10); G.dispose ();//similar to the off-stream imageio.write in Io (BFI, "JPEG", new FileOutputStream ("f:\\ex\\a.jpg"));//bfi to the canvas, write the canvas to a file JPEG to the specified file format} @Testpublic void Test2 () throws Exception{int width =100;int height=40; BufferedImage BFI =new bufferedimage (width, height, bufferedimage.type_int_rgb); Graphics G=bfi.getgraphics ();//Get the Graphics object can draw//1, set the background (white box) G.setcolor (color.white);//White Brush G.fillrecT (0, 0, width, height);//2, generate random number of string str= "";//Save Data Random rom=new random ();//Set the uppercase and coarse g.setfont of the font (the new font ("a", font.bold,20));//Draw a specific picture for (int i=0;i<4;i++) {int num=rom.nextint (10);//Generate a random number G.setcolor (The New Color (Rom.nextint ( (Rom.nextint), Rom.nextint (256));//Set the color of the brush (random) g.drawstring ("" +num, 20*i, 20+rom.nextint (10));//Draw the line, The position of x increases 20,y coordinates to 201 lines, either online or offline//ps: The position needs to be clear,}//draw some interference lines for (int i = 0; i <; i++) {G.setcolor (new Color Rom.nextint (Rom.nextint), Rom.nextint (256));//Set the color of the brush (random) G.drawline (Rom.nextint (+), Rom.nextint (+), Rom.nextint (+), Rom.nextint (40));//position is also random, x, y value do not exceed Rectangle box}g.dispose (); Imageio.write (BFI, "JPEG", New FileOutputStream ("F:\\ex \\b.jpg "));} Draw the case that can be changed//font can be rotated verification code @testpublic void Test3 () throws Ioexception{int Width=100;int height=40; BufferedImage BFI =new bufferedimage (width, height, bufferedimage.type_int_rgb); Graphics G=bfi.getgraphics (); Graphics2D g2d= (graphics2d) G; Random rom =new random (); G2d.setcolor (color.white);//Set the color of the brush g2d.fillrect (0, 0, width, height);//Draw a white rectangle G2d.setfont (New Font ("A", Font.Bold,)); for (int i=0;i<4;i++) {int Num=rom.nextint ( 10);//rotate, indent affinetransform aff=new affinetransform ()//aff.rotate (Math.random (), i*18, height-20);//Rotate Aff.scale ( 0.6+math.random (), 0.6+math.random ());//Zoom G2d.setcolor (New Color (Rom.nextint), Rom.nextint (n), Rom.nextint ( )); G2d.settransform (AFF); G2d.drawstring ("" +num, I*18, height-25);} G2d.dispose (); Imageio.write (BFI, "JPEG", New FileOutputStream ("f:\\ex\\c.jpg"));}}






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. I hope you have more advice

Easy to learn the generation of verification codes in Web pages (JAVA)

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.