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);
}
}
}
JAVA后端代码绘制验证码
于 2024-08-01 08:28:54 首次发布