Java实现验证码的小工具类

public class VerifyCodeUtil {
    public static void main(String[] args) throws IOException {
        String str = "123456789abdefghijkmnopqrstuvwxyzABCDEFHJKLMNPQRSTUVWXYZ";
        String code = drawVerifyCode(new FileOutputStream("F:\\1.jpg"),str);
        //当用在servlet或者jsp中时,一般需要将这个方法返回的code保存到session中,用来和用户提交的验证码进行比较判断
        System.out.println(code);
    }
    public static final String drawVerifyCode(OutputStream os,String str) throws IOException {
        if(str == null || str.trim().length() == 0){
            str = "123456789abdefghijkmnopqrstuvwxyzABCDEFHJKLMNPQRSTUVWXYZ";
        }
        int width = 120;
        int height = 40;
        // 创建一个画布
        BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 获取一个画笔
        Graphics2D g = bi.createGraphics();
        // 画图过程
        // 设置画笔的颜色为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        Random random = new Random();
        // 画干扰线
        for (int i = 0; i < 30; i++) {
            g.setColor(new Color(100 + random.nextInt(105),100 + random.nextInt(105), 100 + random.nextInt(105)));
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),
                    random.nextInt(height));
        }
        // 绘制黑色边框;先画干扰线,后画边框,是为了避免干扰先覆盖到边框 
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        //设置画笔的字体
        g.setFont(new Font("微软雅黑", Font.BOLD, 22));
        StringBuilder sb = new StringBuilder();
        // 向画布中随机输出几个字符
        for (int i = 1; i < 5; i++) {
            // 为字 生成旋转角度
            double jiaodu = random.nextInt(40) - 30;
            // 将旋转角度 换算弧度
            double theta = jiaodu / 180 * Math.PI;
            g.rotate(theta, 20 * i, 0);
            int index = random.nextInt(str.length());
            char c = str.charAt(index);
            sb.append(c);
            // 随机设置画笔颜色
            g.setColor(new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100)));
            //画出字符
            g.drawString(c + "", 20 * i, 30);
            g.rotate(-theta, 20 * i, 0);
        }
        // 内存中资源 释放
        g.dispose();
        // 将画布输出到文件中
        ImageIO.write(bi, "JPG", os);
        return sb.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若♡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值