关注互联网应用及运维技术的个人博客

java图形验证码工具类

1、字符不旋转,比较清晰

package cn.yepk.common.tools;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


/**
 * @author yepk
 * @apiNote 验证码工具类
 * @date 2019/7/10 14:08
 */
public class ValidateCode {

    /**
     * 验证码宽度 默认值:90
     **/
    private int width = 90;
    /**
     * 验证码高度 默认值:40
     **/
    private int height = 40;
    /**
     * 验证码个数  默认值:4
     **/
    private int codeCount = 4;
    /**
     * 混淆线个数  默认值:19
     **/
    private int lineCount = 19;
    /**
     * 字体大小像素
     **/
    private int fontSize = 20;
    /**
     * 存储session中的key值 默认值:"validateCode"
     **/
    private String sessionKey = "CustomerCode";

    public ValidateCode() {
    }

    /**
     * @param width    验证码宽度
     * @param height   验证码高度
     * @param fontSize 字体大小像素
     */
    public ValidateCode(int width, int height, int fontSize) {
        this.width = width;
        this.height = height;
        this.fontSize = fontSize;
    }

    /**
     * @param width      验证码宽度
     * @param height     验证码高度
     * @param fontSize   字体大小像素
     * @param sessionKey 存储session中的key值
     */
    public ValidateCode(int width, int height, int fontSize, String sessionKey) {
        this.width = width;
        this.height = height;
        this.fontSize = fontSize;
        this.sessionKey = sessionKey;
    }

    /**
     * @param width      验证码宽度
     * @param height     验证码高度
     * @param codeCount  验证码个数
     * @param fontSize   字体大小像素
     * @param sessionKey 存储session中的key值
     */
    public ValidateCode(int width, int height, int codeCount, int fontSize, String sessionKey) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.fontSize = fontSize;
        this.sessionKey = sessionKey;
    }

    /**
     * @param width      验证码宽度
     * @param height     验证码高度
     * @param codeCount  验证码个数
     * @param lineCount  混淆线个数
     * @param fontSize   字体大小像素
     * @param sessionKey 存储session中的key值
     */
    public ValidateCode(int width, int height, int codeCount, int lineCount, int fontSize, String sessionKey) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
        this.fontSize = fontSize;
        this.sessionKey = sessionKey;
    }


    private char[] codeSequence = {'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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    /**
     * @param request  请求
     * @param response 响应
     * @apiNote
     * @author yepk
     * @date 2019/7/10 14:10
     */
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        //定义随机数类
        Random random = new Random();
        //定义存储验证码的类
        StringBuilder builderCode = new StringBuilder();
        //定义画布
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //得到画笔
        Graphics graphics = buffImg.getGraphics();
        //1.设置颜色,画边框
        graphics.setColor(Color.gray);
        graphics.drawRect(0, 0, width, height);
        //2.设置颜色,填充内部
        graphics.setColor(Color.white);
        graphics.fillRect(1, 1, width - 2, height - 2);
        //3.设置干扰线
        // g.setColor(Color.gray);
        for (int i = 0; i < lineCount; i++) {
            int r = (int) Math.floor(Math.random() * 256);
            int g = (int) Math.floor(Math.random() * 256);
            int b = (int) Math.floor(Math.random() * 256);
            graphics.setColor(new Color(r, g, b, 255));
            graphics.drawLine(random.nextInt(width), random.nextInt(width), random.nextInt(width), random.nextInt(width));
        }
        //4.设置验证码
        graphics.setColor(Color.blue);
        //4.1设置验证码字体
        graphics.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, fontSize));
        for (int i = 0; i < codeCount; i++) {
            char c = codeSequence[random.nextInt(codeSequence.length)];
            builderCode.append(c);
            graphics.drawString(c + "", ((width / codeCount) * i + 2), height * 4 / 5);
        }
        try {
            //5.输出到屏幕
            ServletOutputStream sos = response.getOutputStream();
            ImageIO.write(buffImg, "png", sos);
            //6.保存到session中
            HttpSession session = request.getSession();
            session.setAttribute("" + sessionKey + "", builderCode.toString());
            //7.禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");
            //8.关闭sos
            sos.close();
        } catch (IOException ignored) {
        }

    }
}

2、字符旋转 字符颜色随机 加干扰点

package cn.yepk.common.tools;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author yepk
 * @apiNote 验证码工具类
 * @date 2019/7/10 14:28
 */
public class ValidateCodeUtil {

    /**
     * 验证码宽度 默认值:100
     **/
    private int width = 100;
    /**
     * 验证码高度 默认值:30
     **/
    private int height = 30;
    /**
     * 验证码个数  默认值:4
     **/
    private int codeCount = 4;
    /**
     * 混淆线个数  默认值:10
     **/
    private int lineCount = 10;

    private int pointCount = 20;
    /**
     * 字体大小像素
     **/
    private int fontSize = 25;
    /**
     * 存储session中的key值
     **/
    private String sessionKey = "CustomerCode";


    public ValidateCodeUtil(String sessionKey) {
        this.sessionKey = sessionKey;
    }

    /**
     * @param width    验证码宽度
     * @param height   验证码高度
     * @param fontSize 字体大小像素
     */
    public ValidateCodeUtil(int width, int height, int fontSize) {
        this.width = width;
        this.height = height;
        this.fontSize = fontSize;
    }

    /**
     * @param width      验证码宽度
     * @param height     验证码高度
     * @param fontSize   字体大小像素
     * @param sessionKey 存储session中的key值
     */
    public ValidateCodeUtil(int width, int height, int fontSize, String sessionKey) {
        this.width = width;
        this.height = height;
        this.fontSize = fontSize;
        this.sessionKey = sessionKey;
    }

    /**
     * @param width      验证码宽度
     * @param height     验证码高度
     * @param codeCount  验证码个数
     * @param fontSize   字体大小像素
     * @param sessionKey 存储session中的key值
     */
    public ValidateCodeUtil(int width, int height, int codeCount, int fontSize, String sessionKey) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.fontSize = fontSize;
        this.sessionKey = sessionKey;
    }

    /**
     * @param width      验证码宽度
     * @param height     验证码高度
     * @param codeCount  验证码个数
     * @param lineCount  混淆线个数
     * @param pointCount 混淆点个数
     * @param fontSize   字体大小像素
     * @param sessionKey 存储session中的key值
     */
    public ValidateCodeUtil(int width, int height, int codeCount, int lineCount, int pointCount, int fontSize, String sessionKey) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
        this.pointCount = pointCount;
        this.fontSize = fontSize;
        this.sessionKey = sessionKey;
    }

    /**
     * @param request  请求
     * @param response 响应
     * @apiNote
     * @author yepk
     * @date 2019/7/10 14:10
     */
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        BufferedImage image = getValidateCodeImage(width, height, codeCount, lineCount, pointCount);
        String validateCode = this.validateCode.toString();
        try {
            //5.输出到屏幕
            ServletOutputStream sos = response.getOutputStream();
            ImageIO.write(image, "png", sos);
            //6.保存到session中
            HttpSession session = request.getSession();
            session.setAttribute("" + sessionKey + "", validateCode);
            //7.禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");
            //8.关闭sos
            sos.close();
        } catch (IOException ignored) {
        }
    }

    private Random r = new Random();

    /**
     * 计算字体大小
     **/
    private static final double FACTOR = 0.75;
    /**
     * 只保存一次当前验证码
     **/
    private StringBuilder validateCode = new StringBuilder();

    private static final char[] CODE_SEQUENCE = {'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 BufferedImage getValidateCodeImage(int width, int height, int codeCount, int lineCount,
                                               int pointCount) {
        // 构建一副图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取设置图片内容的画笔
        Graphics g = image.getGraphics();
        // 设置背景
        setBackGround(g, width, height);
        // 设置边框
        setBorder(g);
        // 添加干扰线
        drawRandomLine(g, width, height, lineCount);
        // 添加干扰点
        drawRandomPoint(g, width, height, pointCount);
        // 写随机数
        drawRandomNum((Graphics2D) g, width, height, codeCount);
//        g.dispose();
        return image;
    }

    private void drawRandomNum(Graphics2D g, int width, int height, int length) {
        int x = 3;
        int size = fontSize;
        int y = height / 2 + size / 2 - 5;
        g.setFont(new Font("宋体", Font.PLAIN, size));
        // 文字旋转度数
        int degree = 0;
        for (int i = 0; i < length; i++) {
            g.setColor(getRandomColor(0));
            // 设置旋转角度
            degree = r.nextInt(60) - 30;
            // 进行文字旋转
            g.rotate((degree * Math.PI) / 180, x, y);
            // 保存本次数组角标
            int index = r.nextInt(CODE_SEQUENCE.length);
            g.drawString(String.valueOf(CODE_SEQUENCE[index]), x, y);
            // 还原旋转角度
            g.rotate(-(degree * Math.PI) / 180, x, y);
            x = x + width / length;
            // 记录随机验证码
            this.validateCode.append(CODE_SEQUENCE[index]);
        }
    }

    private void drawRandomPoint(Graphics g, int width, int height, int randomPointCount) {
        int x, y;
        for (int i = 0; i < randomPointCount; i++) {
            g.setColor(getRandomColor(0));
            x = r.nextInt(width);
            y = r.nextInt(height);
            g.drawLine(x, y, x, y);
        }
    }

    private void drawRandomLine(Graphics g, int width, int height, int randomLineCount) {
        for (int i = 0; i < randomLineCount; i++) {
            g.setColor(getRandomColor(0));
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
    }

    private static void setBorder(Graphics g) {

    }

    private void setBackGround(Graphics g, int width, int height) {
        g.setColor(getRandomColor(220));
        g.fillRect(0, 0, width, height);
    }

    /**
     * @param low 颜色值
     * @return java.awt.Color
     * @apiNote 获取一个随机颜色
     * @author yepk
     * @date 2019/7/10 14:36
     */
    private Color getRandomColor(int low) {
        int sub = 255 - low + 1;
        return new Color(low + r.nextInt(sub), low + r.nextInt(sub), low + r.nextInt(sub));
    }

}
赞(0)
未经允许不得转载:飞天狒狒 » java图形验证码工具类

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址