package com.oracle.cl;
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;
public class ValidateCode
{
public static void main(String[] args) throws IOException
{
Random random=new Random();
// 默认背景为黑色
BufferedImage image=new BufferedImage(100,50,BufferedImage.TYPE_INT_RGB);
// 获取画笔
Graphics graphics = image.getGraphics();
// 默认填充为白色
graphics.fillRect(0,0, 100, 50);
// 验证码是由 数字 字母 干扰线 干扰点组成
// 文字素材
String words="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
char[] cs = words.toCharArray();
// 一般验证码为4位数
// 字母+数字
for(int i=0;i<=3;i++)
{
// 设置随机的颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
graphics.setFont(new Font("微软雅黑",Font.BOLD,30));
char c=cs[random.nextInt(cs.length)];
graphics.drawString(c+"", i*20, 30);
}
// 画干扰线
int max=random.nextInt(10);
for(int i=0;i<max;i++)
{
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
graphics.drawLine(random.nextInt(100),random.nextInt(50), random.nextInt(100), random.nextInt(50));
}
// 画干扰点
int max2=random.nextInt(10);
for(int i=0;i<max2;i++)
{
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
graphics.drawOval(random.nextInt(80), random.nextInt(40), random.nextInt(5), random.nextInt(10));
}
ImageIO.write(image, "jpg", new File("D:\\验证码.jpg"));
}
}
生成的验证码: