JAVA后端代码绘制验证码

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.util.Random;

public class Test {
    public static void main(String[] args) {
        int width = 100;
        int height = 50;
        // 绘制背景
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics2D graphics = env.createGraphics(image);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);

        Random random = new Random();
        // 绘制验证码
        StringBuilder captcha = new StringBuilder();
        String[] fonts = env.getAvailableFontFamilyNames();
        for (int i = 0; i < 4; i++) {
            String code = String.valueOf(random.nextInt(10));
            captcha.append(code);
            // 设置字体
            graphics.setFont(new Font(fonts[random.nextInt(fonts.length)], Font.BOLD, 30 + random.nextInt(20)));
            // 设置颜色
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            // 绘制验证码
            graphics.drawString(code, 20 * i + 10, 25 + random.nextInt(25));
        }
        // 绘制干扰线
        for (int i = 0; i < 6; i++) {
            //设置画笔随机颜色
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            //生成直线的坐标,两点确定一条直线
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }
        graphics.dispose();
        System.out.println("captcha: " + captcha.toString());
        try {
            ImageIO.write(image, "jpg", new FileOutputStream("路径+文件名.jpg"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

或者直接下载文件,提取码:e1bf

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值