生成圖形驗證碼工具類: VerificationCodeUtil
package com.merce.woven.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* @author chuan
* @date 2019-05-05
* @desc 圖形驗證碼生成
*/
public class VerificationCodeUtil {
// 驗證碼字符集
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
// 驗證碼位數
private static final int CODE_SIZE = 4;
// 圖片上干擾線數量
private static final int LINES = 5;
// 圖片寬度
private static final int IMAGE_WIDTH = 80;
// 圖片高度
private static final int IMAGE_HEIGHT = 40;
// 圖片字體大小
private static final int FONT_SIZE = 30;
/**
* 生成隨機驗證碼及圖片
* Object[0]:驗證碼字符串;
* Object[1]:驗證碼圖片。
*/
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
// 1.創建空白圖片
BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.獲取圖片畫筆
Graphics graphic = image.getGraphics();
// 3.設置畫筆顏色
graphic.setColor(Color.LIGHT_GRAY);
// 4.繪製矩形背景
graphic.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
// 5.畫隨機字符
Random ran = new Random();
for (int i = 0; i < CODE_SIZE; i++) {
// 取隨機字符索引
int n = ran.nextInt(chars.length);
// 設置隨機顏色
graphic.setColor(getRandomColor());
// 設置字體大小
graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 畫字符
graphic.drawString(chars[n] + "", i * IMAGE_WIDTH / CODE_SIZE, IMAGE_HEIGHT * 2 / 3);
// 記錄字符
sb.append(chars[n]);
}
// 6.畫干擾線
for (int i = 0; i < LINES; i++) {
// 設置隨機顏色
graphic.setColor(getRandomColor());
// 隨機畫線
graphic.drawLine(ran.nextInt(IMAGE_WIDTH), ran.nextInt(IMAGE_HEIGHT),
ran.nextInt(IMAGE_WIDTH), ran.nextInt(IMAGE_HEIGHT));
}
// 7.返回驗證碼和圖片
return new Object[]{sb.toString(), image};
}
/**
* 獲取隨機背景顏色(RGB)
*/
private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
return color;
}
}
通過接口返回給前端:
(1)Spring-Jersey的rest接口返回方式:
@GET
@Path("/getCode")
public void getCode() throws IOException {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
HttpServletResponse response = servletRequestAttributes.getResponse();
HttpSession session = servletRequestAttributes.getRequest().getSession();
//利用圖片工具生成圖片,第一個參數是生成的驗證碼,第二個參數是生成的圖片
Object[] objs = VerificationCodeUtil.createImage();
//將驗證碼存入Session
session.setAttribute("code",objs[0]);
//禁止圖像緩存
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//將圖片輸出給瀏覽器
BufferedImage image = (BufferedImage) objs[1];
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);
}