【生成图片验证码】

生成图片验证码

  1. 工具类
package com.example.demo.utils;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class ValidateCodeUtil {
    protected static char[] minCh = new char[]{'0', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    static Random random = new Random();

    public static String random(int strLen) {
        return random(minCh, strLen);
    }

    public static String random(char[] charArr, int strLen) {
        if (strLen <= 0) {
            if (strLen == 0) {
                return "";
            } else {
                throw new IllegalArgumentException();
            }
        } else {
            Random random = new Random();
            StringBuilder result = new StringBuilder();

            for (int i = 0; i < strLen; ++i) {
                int num = random.nextInt(charArr.length);
                result.append(charArr[num]);
            }

            return result.toString();
        }
    }

    private static Color getRandColor() {
        Random random = new Random();
        Color[] color = new Color[10];
        color[0] = new Color(32, 158, 25);
        color[1] = new Color(218, 42, 19);
        color[2] = new Color(31, 75, 208);
        color[3] = new Color(0, 102, 182);
        color[4] = new Color(171, 0, 85);
        return color[random.nextInt(5)];
    }

    public static Font getFont() {
        Random random = new Random();
        Font[] font = new Font[]{new Font("Ravie", 1, 30), new Font("Antique Olive Compact", 1, 30), new Font("Forte", 1, 30), new Font(
                "Wide Latin", 1, 30), new Font("Gill Sans Ultra Bold", 1, 30)};
        font[5] = new Font("Courier New", 1, 30);
        return font[random.nextInt(5)];
    }

    public static byte[] render(String randomStr, int width, int height) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage bi = new BufferedImage(width, height, 13);
        Graphics2D g = (Graphics2D) bi.getGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Courier New", 1, 30));
        g.setColor(Color.BLACK);
        String[] str1 = new String[randomStr.length()];

        int i;
        int x;
        int y;
        for (i = 0; i < str1.length; ++i) {
            str1[i] = randomStr.substring(i, i + 1);
            y = (i + 1) % 3;
            if (y == random.nextInt(7)) {
                x = 30 - random.nextInt(7);
            } else {
                x = 30 + random.nextInt(7);
            }

            g.setColor(getRandColor());
            g.drawString(str1[i], 20 * i + 10, x);
        }

        for (i = 0; i < 100; ++i) {
            x = random.nextInt(width);
            y = random.nextInt(height);
            Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
            g.setColor(color);
            g.drawOval(x, y, 0, 0);
        }

        for (i = 0; i < 15; ++i) {
            x = random.nextInt(width);
            y = random.nextInt(height);
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
            g.setColor(color);
            g.drawLine(x, y, x1, y1);
        }

        g.dispose();
        ImageIO.write(bi, "png", out);
        return out.toByteArray();
    }
}

  1. 控制层调用
package com.example.demo.controller;

import com.example.demo.utils.ValidateCodeUtil;
import io.swagger.annotations.ApiOperation;
import org.mapstruct.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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.io.IOException;
import java.io.OutputStream;

/**
 * @Author HOUJL
 * @Date 2022/3/22
 * @Description:生成图片验证码
 */
@RestController
@RequestMapping("/qrCode")
public class QRCodeController {
    private static final Logger LOGGER = LoggerFactory.getLogger(QRCodeController.class);

    /**
     * 生成图片验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/generateQRCode", method = RequestMethod.GET)
    @ApiOperation("获取图形验证码")
    public void generateQRCode(@Context HttpServletRequest request, HttpSession session
            , @Context HttpServletResponse response) {
        LOGGER.info("generateQRCode session id: {}", session.getId());
        try {
            String code = ValidateCodeUtil.random(4);
            LOGGER.debug("生成的验证码code是:{}", code);
            byte[] codeImg = ValidateCodeUtil.render(code, 100, 50);
            // 禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            // 将图像输出到Servlet输出流中。
            ServletOutputStream sos = response.getOutputStream();
            sos.write(codeImg);
            //ImageIO.write(codeImg, "jpeg", sos);
            sos.flush();
            sos.close();
        } catch (IOException e) {
            LOGGER.error("generateQRCode error : {}", e);
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值