// 数字和字母的组合
//String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
//String baseNumLetter = "2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY";
String baseNumLetter = "123456789";
StringBuffer sBuffer = new StringBuffer();
int x = 10; // 旋转原点的 x 坐标
String ch = "";
Random random = new Random();
Color textColor = getRandomColor();
for (int i = 0; i < 4; i++) {
// graphics.setColor(getRandomColor());
graphics.setColor(textColor);
// 设置字体旋转角度
int degree = random.nextInt() % 30; // 角度小于30度
int dot = random.nextInt(baseNumLetter.length());
ch = baseNumLetter.charAt(dot) + "";
sBuffer.append(ch);
// 正向旋转
graphics.rotate(degree * Math.PI / 180, x, 45);
//graphics.drawString(ch, x, 45);
graphics.drawString(ch, x, 30);
// 反向旋转
graphics.rotate(-degree * Math.PI / 180, x, 45);
//x += 48;
x += 30;
}
// 画干扰线
for (int i = 0; i < 6; i++) {
// 设置随机颜色
graphics.setColor(getRandomColor());
// 随机画线
graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),
random.nextInt(height));
}
// 添加噪点
// for (int i = 0; i < 30; i++) {
// int x1 = random.nextInt(width);
// int y1 = random.nextInt(height);
// graphics.setColor(getRandomColor());
// graphics.fillRect(x1, y1, 2, 2);
// }
return sBuffer.toString();
}
private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
return color;
}
public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
// {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
//可选字符
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
//背景色
private Color bgColor = new Color(255, 255, 255);
private String text ;
//生成随机的颜色
private Color randomColor () {
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}
//生成随机字体
private Font randomFont () {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4); //生成随机样式,0:无样式,1:粗体,2:斜体,3:粗体+斜体
int size = r.nextInt(5) + 24; //生成随机字号
return new Font(fontName, style, size);
}
//画干扰线
private void drawLine (BufferedImage image) {
int num = 3; //总共画三条干扰线
Graphics2D g2 = (Graphics2D)image.getGraphics();
for(int i = 0; i < num; i++) { //生成两个点的左边,即4个值
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
g2.setColor(Color.BLUE); //设置干扰线颜色为蓝色
g2.drawLine(x1, y1, x2, y2);
}
}
//随机生成一个字符
private char randomChar () {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}