利用BufferedImage生成验证码

利用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();
	//1000,9999
	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://img2018.cnblogs.com/blog/1560559/201907/1560559-20190728143427154-1042121002.png)
posted @ 2019-07-28 14:34  等不到时光等天亮  阅读(544)  评论(1编辑  收藏  举报