puzhibing
2024-01-03 168d852672f8f671a01d6f0f053349d0d321ec7c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.dsh.guns.modular.system.controller.util;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
 
public class CaptchaImageGenerator {
    public static BufferedImage generateCaptchaImage(String captcha, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = image.createGraphics();// 设置背景色
        graphics2D.setColor(Color.WHITE);
        graphics2D.fillRect(0, 0, width, height);
        // 设置验证码字体
        Font font = new Font("Arial", Font.BOLD, 48);
        graphics2D.setFont(font);
        // 设置验证码颜色
        // graphics2D.setColor(Color.BLACK);
        // 在图片上绘制验证码字符串
        int x = (width - graphics2D.getFontMetrics().stringWidth(captcha))
                / 2;
        int y = height / 2;
        graphics2D.drawString(captcha, x, y);
        graphics2D.dispose();
        return image;
    }
}