利用BufferedImage生成验证码
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.text.StyledEditorKit.BoldAction;
public class Image {
Random random = new Random();
public int getnum() {
int num = random.nextInt(9000)+1000;
return num;
}
public Color getcolor() {
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
Color color = new Color(r, g, b);
return color;
}
public BufferedImage draw() {
BufferedImage image = new BufferedImage(160,60,BufferedImage.TYPE_INT_BGR);
Graphics graphics = image.getGraphics();
graphics.fillRect(0, 0, 160, 60);
for(int i=0;i<60;i++) {
int xb = random.nextInt(160);
int yb = random.nextInt(60);
int xr = random.nextInt(xb+10);
int yr = random.nextInt(yb+10);
graphics.setColor(getcolor());
graphics.drawLine(xb, yb, xr, yr);
}
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("楷体",Font.BOLD,30));
graphics.drawString(getnum()+"",60,30);
return image;
}
public static void main(String[] args) throws IOException {
Image image = new Image();
BufferedImage draw = image.draw();
ImageIO.write(draw, "jpeg", new File("a.jpeg"));
}
}
![](https:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步