java Graphic verification code generation tool class web page verification code
- 2020-06-15 09:01:44
- OfStack
Do captcha recently, reference online case, found that there are many problems, specially modified and improved.
Verification code generator:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;
/**
* Captcha generator
*
* @author
*/
public class ValidateCode {
// Width of picture.
private int width = 160;
// Height of the picture.
private int height = 40;
// Number of captcha characters
private int codeCount = 5;
// Number of captchAs interfering lines
private int lineCount = 150;
// Verification code
private String code = null;
// Captcha image Buffer
private BufferedImage buffImg = null;
// Captcha range , To get rid of 0( digital ) and O( pinyin ) Confusable ( lowercase 1 and L You can also get rid of it , Capital doesn't matter )
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'};
/**
* Default constructor , Set default parameters
*/
public ValidateCode() {
this.createCode();
}
/**
* @param width Image width
* @param height Pictures of high
*/
public ValidateCode(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
* @param width Image width
* @param height Pictures of high
* @param codeCount The number of characters
* @param lineCount Number of interfering 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);// The width of each character ( Leave the left and the right 1 A character )
fontHeight = height - 2;// Font height
codeY = height - 4;
// image buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// Random number generation
Random random = new Random();
// Fill the image with white
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// Create a font , You can change it to something else
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
// Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, fontHeight);
g.setFont(font);
for (int i = 0; i < lineCount; i++) {
// Set random start and end coordinates
int xs = random.nextInt(width);//x Coordinate began
int ys = random.nextInt(height);//y Coordinate began
int xe = xs + random.nextInt(width / 8);//x Coordinates of the end
int ye = ys + random.nextInt(height / 8);//y Coordinates of the end
// Produces a random color value so that each interference line output will have a different color value.
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 Record randomly generated captcha
StringBuffer randomCode = new StringBuffer();
// Randomly generated codeCount A two-character captcha.
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
// Produces a random color value so that each character output will have a different color value.
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);
// Will produce the 4 Random number combination in 1 Up.
randomCode.append(strRand);
}
// will 4 The bit-digit captcha is saved to Session In the.
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;
}
/**
* Test functions , Generate by default to d disc
* @param args
*/
public static void main(String[] args) {
ValidateCode vCode = new ValidateCode(160,40,5,150);
try {
String path="D:/"+new Date().getTime()+".png";
System.out.println(vCode.getCode()+" >"+path);
vCode.write(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below is the page JS call captcha
// Refresh the image
function changeImg() {
var imgSrc = $("#imgObj");
var url = imgSrc.attr("src");
imgSrc.attr("src", changeUrl(url));
}
// In order to make each generated image no 1 The browser is not allowed to read the cache, so a timestamp is required
function changeUrl(url) {
var timestamp = (new Date()).valueOf();
var index = url.indexOf("?");
console.log(index);
if (index > 0) {
url = url.substring(0, url.indexOf("?"));
}
console.log(url);
if ((url.indexOf("&") > 0)) {
url = url + " x tamp=" + timestamp;
console.log(url);
} else {
url = url + "?timestamp=" + timestamp;
console.log(url);
}
return url;
}
Below is the controller layer output captcha
/**
* Response captcha page
* @return
*/
@RequestMapping(value="/validateCode")
public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
// Set the type format of the response to an 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 = request.getSession();
ValidateCode vCode = new ValidateCode(120,40,5,100);
session.setAttribute("code", vCode.getCode());
vCode.write(response.getOutputStream());
return null;
}
Below is the controller layer to verify that the verification code input is correct
String code = request.getParameter("code");
HttpSession session = request.getSession();
String sessionCode = (String) session.getAttribute("code");
if (!StringUtils.equalsIgnoreCase(code, sessionCode)) { // Ignore captcha case
throw new RuntimeException(" The captcha does not correspond code=" + code + " sessionCode=" + sessionCode);
}