java生成图形验证码

GoogleVip8 7月前 ⋅ 402 阅读

辅助工具类

public interface DZFStringUtil {
    String Code200 = "200";
    String Code9999 = "9999";
    String SUCCESSFUL = "成功";
    String FAILURE = "失败";
    String IMAGECODE = "imageCode";
    String IMAGECODETIME = "imageCodeTime";
    String VerificationCodeError = "验证码错误";
    String VerificationCodeMakeError = "验证码生成错误";
    String IMAGECODENOTNULL = "验证码不能为空";
    String PHONENOTNULL = "验证码不能为空";
    String PWDNOTNUMM = "密码不能为空";
    String ISNOTEMPTY = "参数不能为空";
    String USERIDNOTNULL = "userId不能为空";
    String LOGINERRROR = "手机号或者密码错误";
    String PHONEEXISTING = "该手机号已经注册";
    String TooManyRequests = "请求太频繁";
    String USERNOTNULL = "用户不存在";
    String LOGINNOTNULL = "请先登录";
    String PHONEPARTNERISNOTEMPTY = "该手机号已有合伙人";
    String WEIXINPARTNERISNOTEMPTY = "该微信号已有合伙人";
    String JPG = "JPG";
    String BASE64IMAGE = "data:image/jpg;base64,";
    String USERLOGIN = "userLogin";
    String PHONE = "phone";
    String PARTNERUSERID = "partner_user_id";
    String ISEMPTY = "";
    String PERCENT = "%";

    int ZERO = 0;
    int ONE = 1;
    int TWO = 2;
    int THREE = 3;
    int FOUR = 4;
    int FIVE = 5;
    int SIX = 6;
    int SEVEN = 7;
    int NINE = 9;
    int TEN = 10;
    int FIFTEEN = 15;
    int TWENTY = 20;
    int THIRTY = 30;
    int FORTY = 40;
    int FORTYFIVE = 45;
    int TWENTYSIX = 26;
    int SIXTYFIVE = 65;
    int NINETYSEVEN = 97;
    int OneHundred = 100;
    int TwoHundredFiftyFive = 255;

    int IMAGECODEWIDTH = 120;
    int IMAGECODEHEIGHT = 60;

}

生成图形验证码

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import static DZFStringUtil.*;

@Slf4j
public class ImageCodeUtil {
    private static final Color[] COLORS = {new Color(170, 43, 47), new Color(250, 10, 11), new Color(7, 5, 137), new Color(255, 165, 0)};

    /**
     * 校验图形验证码
     *
     * @param request
     * @param imageCode
     * @return
     */
    public static boolean checkImageCode(HttpServletRequest request, String imageCode) {
        String imageCodeOld = (String) request.getSession().getAttribute(IMAGECODE);
        if (imageCodeOld == null) {
            log.error("请先获取验证码");
            return false;
        }
        log.debug("原验证码{},输入的验证码{}", imageCodeOld, imageCode);
        request.getSession().removeAttribute(IMAGECODE);
        return imageCodeOld.equals(imageCode);
    }

    /**
     * 生成图形验证码
     *
     * @param request
     */
    public static String makeImageCode(HttpServletRequest request) {
        BufferedImage bufferedImage = new BufferedImage(IMAGECODEWIDTH, IMAGECODEHEIGHT, BufferedImage.TYPE_INT_BGR);
        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.setColor(new Color(TwoHundredFiftyFive, TwoHundredFiftyFive, TwoHundredFiftyFive));
        graphics.fillRect(ZERO, ZERO, IMAGECODEWIDTH, IMAGECODEHEIGHT);

        String string = ISEMPTY;
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = ZERO; i < FOUR; i++) {
            string = String.valueOf(random.nextInt(NINE));

            AffineTransform affineTransform = new AffineTransform();
            affineTransform.rotate(Math.toRadians(random.nextInt(FORTYFIVE) - random.nextInt(FORTYFIVE)), ZERO, ZERO);
            Font font = new Font(IMAGECODE, Font.PLAIN, TWENTY);
            Font rotatedFont = font.deriveFont(affineTransform);

            graphics.setFont(rotatedFont);
            graphics.setColor(COLORS[i]);

            int x = TWENTYSIX * i + TEN + (random.nextInt(NINE) - random.nextInt(NINE));
            int y = FORTY + (random.nextInt(TWENTY) - random.nextInt(TWENTY));
            graphics.drawString(string, x, y);

            stringBuffer.append(string);
        }
        for (int i = ZERO; i < FOUR; i++) {
            int x1 = (int) (Math.random() * IMAGECODEWIDTH);
            int x2 = (int) (Math.random() * IMAGECODEWIDTH);
            int y1 = (int) (Math.random() * IMAGECODEHEIGHT);
            int y2 = (int) (Math.random() * IMAGECODEHEIGHT);
            graphics.setColor(new Color(ZERO, ZERO, ZERO));
            graphics.drawLine(x1, y1, x2, y2);
        }
        for (int i = ZERO; i < OneHundred; i++) {
            int x = (int) (Math.random() * IMAGECODEWIDTH);
            int y = (int) (Math.random() * IMAGECODEHEIGHT);
            int r = (int) (Math.random() * TwoHundredFiftyFive);
            int g = (int) (Math.random() * TwoHundredFiftyFive);
            int b = (int) (Math.random() * TwoHundredFiftyFive);
            graphics.setColor(new Color(r, g, b));
            graphics.drawOval(x, y, TWO, TWO);
            graphics.setColor(new Color(r, g, b));
            graphics.fillOval(x, y, THREE, THREE);
        }
        log.debug("生成的图片验证码:{}", stringBuffer);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        request.getSession().setAttribute(IMAGECODE, stringBuffer.toString());
        request.getSession().setAttribute(IMAGECODETIME, System.currentTimeMillis());
        try {
            ImageIO.write(bufferedImage, JPG, outputStream);
        } catch (IOException e) {
            log.error(VerificationCodeMakeError, e);
        }
        byte[] bytes = outputStream.toByteArray();
        return BASE64IMAGE + Base64.encodeBase64String(bytes);
    }
}

全部评论: 0

    我有话说: