Springboot 生成验证码

效果图

code.jpeg

代码, 直接复制使用

    private static final Font font = new Font(null, Font.ITALIC, 50);
    private static final String CODE_CHARS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";

    /**
     * 检查验证码
     * @param check 要检测的验证码
     * @param codeId 验证码的id
     * @return true 通过, false 失败
     */
    public static boolean checkCode(String check, String codeId){
        String id = getCodeId(check);
        if (id == null) return false;
        if (codeId == null) return false;
        return id.equalsIgnoreCase(codeId);
    }


    /**
     * 生成验证码图片
     * @param len 验证码长度
     * @param outputStream 验证码输出流
     * @return 验证码的id
     */
    public static String generateCodeImage(int len, OutputStream outputStream){
        String msg = randomCodeStr(len);
        int fontSize = font.getSize();
        int width = fontSize *msg.length()+fontSize;
        int height = (int) (fontSize * 1.5);
        BufferedImage bufferedImage = new BufferedImage(width, height, ColorSpace.TYPE_RGB);
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,width,height);
        //添加干扰线/添加圆圈
        for (int i = 0; i < 12; i++) {
            BasicStroke stroke = new BasicStroke((float) (Math.random() * 1 + 1));
            graphics.setStroke(stroke);
            graphics.setColor(randomColor());
            graphics.drawLine(0, (int)(Math.random()*height), width, (int)(Math.random()*height));
            stroke = new BasicStroke((float) (Math.random() * 1 + 1));
            graphics.setStroke(stroke);
            graphics.setColor(randomColor());
            int x = (int) (Math.random() * width);
            int y = (int) (Math.random() * height);
            int w = (int) (Math.random() * fontSize);
            int h = (int) (Math.random() * fontSize);
            graphics.drawArc(x,y,w,h,0,360);
        }

        for (int i = 0; i < msg.length(); i++) {
            graphics.setColor(randomColor());
            String s = msg.substring(i, i + 1);
            AffineTransform tx = new AffineTransform();
            tx.rotate(Math.toRadians(Math.random()*180-90), (fontSize/2),(-fontSize/2));
            Font deriveFont = font.deriveFont(tx);
            graphics.setFont(deriveFont);
            graphics.drawString(s, i * fontSize+fontSize/2,height - (height- fontSize)/2);
        }

        try {
            graphics.dispose();
            bufferedImage.flush();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            outputStream.flush();
            return getCodeId(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String getCodeId(String code){
        String s = code.toLowerCase();
        try {
            MessageDigest instance = MessageDigest.getInstance("MD5");
            instance.update(s.getBytes());
            byte[] result = instance.digest();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < result.length; i++) { 
                // 你自己的处理方法
                builder.append(String.format("%02x", result[i]));
            }
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }



    private static Color randomColor(){
        int red = (int) (Math.random()*255);
        int blue = (int) (Math.random()*255);
        int green = (int) (Math.random()*255);
        String format = String.format("#%02x%02x%02x", red, green, blue);
        return Color.decode(format);
    }

    private static String randomCodeStr(int len){
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < len; i++) {
            int idx = (int) ((Math.random() * CODE_CHARS.length()*1000)%CODE_CHARS.length());
            String s = CODE_CHARS.substring(idx, idx + 1);
            buffer.append(s);
        }
        return buffer.toString();
    }

你可能感兴趣的:(Springboot 生成验证码)