后端生成base64图片验证码

public CommonResult<String> getCode(HttpServletRequest request, HttpServletResponse response){
        //生成图片宽度
        int width = 130;
        int height = 45;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.setColor(Color.white);//验证码背景色
        g.fillRect(0,0,width,height);
        Random random = new Random();
        String checkCode = getCheckCode();
        //把验证码放到session中
        request.getSession().setAttribute("checkCode_session",checkCode);
        Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
        g.setColor(color);
        g.setFont(new Font("微软雅黑",Font.BOLD,40));
        //向图片写入验证码
        g.drawString(checkCode,15,33);
        //画干扰线
        for(int i = 0;i < 6;i++){
            Color line = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
            g.setColor(line);
            g.drawLine(random.nextInt(width), random.nextInt(height),random.nextInt(width), random.nextInt(height));
        }
        //添加图块噪点
        for(int i = 0;i < 30;i++){
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            Color rect = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
            g.setColor(rect);
            g.fillRect(x,y,2,2);
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"png",stream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String codeImg = Base64Utils.encodeToString(stream.toByteArray());
        return CommonResult.success(codeImg);
    }

    /**
     * 生成四位验证码
     * @return
     */
    public String getCheckCode(){
        //可生成的字符集
        String base = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int size = base.length();
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < 4;i++){
            //产生随机数
            int index = random.nextInt(size);
            char c = base.charAt(index);
            sb.append(c);
        }
        return sb.toString();
    }

前端使用

<img src="data:image/png;base64,${base64资源}">
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容