import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class ImageCode {
public static void main(String[] args) throws IOException {
imageCode();
}
//生成随机验证码的方法
private static void imageCode() throws IOException {
//准备生成验证码的数据
String[] strs={"a","b","c","d","e","f","g","h","i","j","k","m","n","p"
,"q","r","s","t","u","v","w","x","y","z","2","3","4","5","6","7","8","9"};
//准备一个画板,用来承载验证码,参数(宽,高,图片类型)字母,数字,干扰线
int width = 150;
int height = 50;
int imageType = BufferedImage.TYPE_INT_RGB;
BufferedImage image = new BufferedImage(width,height,imageType);
//准备一只画笔
Graphics graphics = image.getGraphics();
//设置画笔的颜色
graphics.setColor(Color.green);
//画填充矩形
graphics.fillRect(0,0,width,height);
//画验证码
//从数组中随机取出4个数据
//设置验证码的位置
Random random = new Random();
int x = 30;
int y=30;
//修改画笔颜色
graphics.setColor(Color.red);
graphics.setFont(new Font("楷体",Font.BOLD,30));
for (int i = 0; i < 4; i++) {
//随机生成num
//获取随机的下标数
Integer num = random.nextInt(strs.length);
String code = strs[num];
//将验证码画到画板上
graphics.drawString(code,x,y);
x=x+25; //修改验证码位置
}
graphics.setColor(Color.blue);
//画干扰线
for (int i = 0; i < 5 ; i++) {
int x1 = random.nextInt(50);
int y1 = random.nextInt(50);
int x2 = random.nextInt(30);
int y2 = random.nextInt(27);
graphics.drawLine(x1,y1,x2,y2);
}
graphics.setColor(Color.orange);
for (int i = 0; i < 5 ; i++) {
int x1 = random.nextInt(30);
int y1 = random.nextInt(20);
int x2 = random.nextInt(50)+120;
int y2 = random.nextInt(30);
graphics.drawLine(x1,y1,x2,y2);
}
//将验证码图片写到本地
ImageIO.write(image,"jpg", new File("C:\Users\xiaoXue\Desktop\imageCode.jpg"));
}
}