Java生成图片验证码

该文章介绍了一个Java编写的验证码工具类,用于生成无干扰线、全阿拉伯数字的图形验证码。代码包括创建图像缓冲区、设置背景和字体颜色、绘制随机字符以及生成干扰线等功能。验证码字符串和对应的图像以JSON格式返回。
摘要由CSDN通过智能技术生成

验证码工具类

图形验证码的长和宽,验证码的位数,干扰线的条数 可以自己定义,我这里选择无干扰线,全阿拉伯数字的验证码。

package com.jeeplus.sys.utils;
import com.alibaba.fastjson.JSONObject;

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

/** 
 * 随机数字验证码
 * @author lgn
 * @date 2023/6/19 9:19
 */
public class VerifyCodeUtil {

    private static final Random random = new Random();
    private static final String[] fontNames = {"宋体", "华文楷体", "黑体", "Georgia", "微软雅黑", "楷体_GB2312"};

    public static JSONObject drawImage() {
        String code = "";
        int width = 116;
        int height = 36;

        //创建图片缓冲区
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

        Graphics2D g = bi.createGraphics();

        //设置背景颜色
        g.setBackground(new Color(255, 255, 255));
        g.clearRect(0, 0, width, height);

        StringBuilder stringBuilder = new StringBuilder();
        //这里只画入四个字符
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";      //随机生成字符,因为只有画字符串的方法,没有画字符的方法,所以需要将字符变成字符串再画
            stringBuilder.append(s);           //添加到StringBuilder里面
            float x = i * 1.0F * width / 4;   //定义字符的x坐标
            g.setFont(randomFont());           //设置字体,随机
            g.setColor(randomColor());         //设置颜色,随机
            g.drawString(s, x, height - 5);
        }
        code = stringBuilder.toString();//获取验证码字符串

        //定义干扰线
        //定义干扰线的数量(3-5条)int num = random.nextInt(max)%(max-min+1) + min;
        int num = 0;
        Graphics2D graphics = (Graphics2D) bi.getGraphics();
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            graphics.setColor(randomColor());
            graphics.drawLine(x1, y1, x2, y2);
        }
        // 释放图形上下文
        g.dispose();
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("codeImg",out.toByteArray());
        jsonObject.put("code",code);

        //out.toByteArray();
        //code;//为了方便取值,直接返回code,
        return jsonObject;
    }

    //随机字体
    private static Font randomFont() {
        int index = random.nextInt(fontNames.length);
        String fontName = fontNames[index];
        int style = random.nextInt(4);         //随机获取4种字体的样式
        int size = random.nextInt(20) % 6 + 15;    //随机获取字体的大小(10-20之间的值)
        return new Font(fontName, style, size);
    }

    //随机颜色
    private static Color randomColor() {
        int r = random.nextInt(225);
        int g = random.nextInt(225);
        int b = random.nextInt(225);
        return new Color(r, g, b);
    }


    //随机字符
    private static char randomChar() {
        //A-Z,a-z,0-9,可剔除一些难辨认的字母与数字
        String str = "0123456789";

        return str.charAt(random.nextInt(str.length()));
    }


    public static void main(String[] args) {
        JSONObject jsonObject = VerifyCodeUtil.drawImage();
        System.out.println(jsonObject);
    }
}

Controller 中使用

将图片的字节流和验证码返回给前端。
1)验证码生成:先生成随机数,把结果存在session中,然后生成图片,并把图片返回前端,当然,也可以存储到redis中
2)验证码验证:前端输入验证码后,后端使用session中存的验证码和前端传参验证码做校验

    /**
     * 获取登陆验证码
     *
     * @throws
     */
    @ApiOperation("获取验证码")
    @ApiLog("获取验证码")
    @GetMapping("/sys/getCode")
    public ResponseEntity getCode() {
        JSONObject jsonObject = VerifyCodeUtil.drawImage();//随机数字验证码
        String uuid = UUID.randomUUID ( ).toString ( );
        //将验证码放入session
        RedisUtils.getInstance ( ).set ( CacheNames.SYS_CACHE_CODE, uuid, jsonObject.getString("code"));
        RedisUtils.getInstance ( ).expire ( CacheNames.SYS_CACHE_CODE, uuid, 60 * 5 );
        return ResponseUtil.newInstance ( ).add ( "codeImg", jsonObject.get("codeImg") ).add ( "uuid", uuid ).ok ( );
    }

ResponseUtil

/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.common.utils;

import org.springframework.http.ResponseEntity;

import java.io.Serializable;
import java.util.HashMap;


/**
 * 返回包装wrapper
 *
 * @author
 */
public class ResponseUtil extends HashMap <String, Object> implements Serializable {

    public static ResponseUtil newInstance() {
        ResponseUtil fragment = new ResponseUtil ( );
        return fragment;
    }

    public ResponseUtil add(String key, Object value) {
        super.put ( key, value );
        return this;
    }

    public ResponseEntity ok() {
        return ResponseEntity.ok ( this );
    }

    public ResponseEntity error() {
        return ResponseEntity.badRequest ( ).body ( this );
    }

    public ResponseEntity ok(String msg) {
        this.put ( "msg", msg );
        return ResponseEntity.ok ( this );
    }

    public ResponseEntity error(String msg) {
        this.put ( "msg", msg );
        return ResponseEntity.badRequest ( ).body ( this );
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值