自定义图形验证码工具

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class ImageUtil {

    public static Map<String, Object> getImageCode(int width, int height) {
        Map<String,Object> returnMap = new HashMap<>();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 设定背景色
        g.setColor(new Color(236, 236, 240));
        g.fillRect(0, 0, width, height);
        //设定字体
        g.setFont(new Font("随便定义字体", Font.BOLD, 14));
        g.setColor(new Color(82, 84, 87));
        //取随机产生的码
        String code = PasswordUtil.generateVerificationCode(5);
//        String code = "GZTWM";
        //4代表4位验证码,如果要生成更多位的认证码,则加大数值
        FontMetrics fm = g.getFontMetrics();
        g.drawString(code,(width-fm.stringWidth(code))/2, 15);
        // 释放图形上下文
        g.dispose();
        try {
            returnMap.put("image",getBufferedImageToBase64(image,"jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        returnMap.put("code",code);
        return returnMap;
    }
    /**
     *  BufferedImage转成 base64
     * @param bufferedImage
     * @param imageFormatName
     * @return
     */
    public static String getBufferedImageToBase64(BufferedImage bufferedImage,String imageFormatName) throws IOException {
        if(StringUtils.isBlank(imageFormatName)){
            imageFormatName = "png";
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, imageFormatName, stream);
        String s = Base64.getEncoder().encodeToString(stream.toByteArray());
        return s;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值