生成图片验证码工具类

首先绘制图片依赖 commons-codec-1.10.jar包,我已上传

package PicCheckCode;

import org.apache.commons.codec.binary.Base64;

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

public class CheckPicCode {
    private static String picCode;

    public static String getPicCode() {
        return picCode;
    }

    public static void setPicCode(String picCode) {
        CheckPicCode.picCode = picCode;
    }

    public static String getCheckCode(){
        //验证码中的字符由数字和大小写字母组成
        String code = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            sb.append(code.charAt(r.nextInt(code.length())));
        }

        return sb.toString();
    }

    public static BufferedImage showPic() throws IOException {
        String code=getCheckCode();
        setPicCode(code);
        int width=80;
        int height=30;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g=image.getGraphics();
        g.setColor(Color.white);
        g.fillRect(0,0,width,height);
        Random r=new Random();
        for (int i=0;i<3;i++){
            g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
            g.drawLine(r.nextInt(80),r.nextInt(30),r.nextInt(80),r.nextInt(80));
        }
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        g.setFont(new Font("黑体",Font.BOLD,24));
        g.drawString(code,15,20);
        g.dispose();//图像生效
        return image;
    }
    public static String encodeBase64ImgCode() throws IOException{
        BufferedImage codeImg=showPic();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(codeImg, "JPEG", out);
        byte[] b = out.toByteArray();
        String imgString = Base64.encodeBase64String(b);
        return "data:image/JPEG;base64," + imgString;
    }

    public static void main(String[] args) throws IOException {
        String base64PicCodeImage = encodeBase64ImgCode();
        String checkCode = getPicCode();
        System.out.println("验证码==》"+checkCode);
        System.out.println("base64图片字符串==》"+base64PicCodeImage);
    }
}

执行main方法,打印结果如下:

新建HTML网页

<html>
<img src="https://img-blog.csdnimg.cn/2022010620593653349.JPEG">
</html>

打开HTML显示如下:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值