Java实现验证码

Java实现验证码

步骤:
1)选取4个随机的字母或数字
2)创建缓冲图片
3)创建绘图对象
4)使用绘图对象绘制随机的字母或数字
5)将生成的验证码输出


代码实现:

 public static void main(String[] args) throws Exception {
        int width = 200;
        int height = 100;
        //缓存图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        //画笔对象
        Graphics graphics = bufferedImage.getGraphics();

        //白色容器
        graphics.setColor(new Color(255, 255, 255));
        graphics.fillRect(0, 0, width, height);

        //验证码,制作开始
        //颜色
        graphics.setColor(new Color(0, 0, 0));
        //字体
        graphics.setFont(new Font("黑体", Font.BOLD, 40));
        //随机码
        String randomCode = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        //进行绘制
        graphics.drawString(randomCode, 54, 64);

        //干扰信息
        //线
        Random r = new Random();
        for (int i = 0; i < 15; i++) {
            graphics.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            graphics.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        //点
        for (int i = 0; i < 150; i++) {
            graphics.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            //开始画点,实质上这是画椭圆,将上半轴半径,左半轴半径设置为0就可以看成是一个点
            graphics.drawOval(r.nextInt(width), r.nextInt(height), 0, 0);
        }

        //输出
        FileOutputStream fos = new FileOutputStream("/Users/liuqiang/Documents/project/gltf-ue/ok.png");
        ImageIO.write(bufferedImage, "png", fos);

        fos.close();
    }

代码解释:

图形的绘制API:
BufferedImage 缓冲图片(保存在内存中的图片)
Graphics 图形
setColor(Color color) 设置颜色
setFont(Font font) 设置字体
fillRect(横坐标,纵坐标,宽,高) 填充矩形
drawLine(横坐标,纵坐标,横坐标,纵坐标) 绘制线条
drawString(String text,横坐标,纵坐标) 绘制文字

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值