import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
public class test {
public static void main(String[] args) throws IOException {
String code = getRandCode(4);
for (int i = 0; i < CODES.length; i++) {
System.out.Int(10));
}
System.out.println(code);
ImageIO.write(new test(160, 40).getValidateCode(code), "png",
new File("d:/a.png"));
}
private static Random random = new Random();
// 定义可选择的字符
private static final char[] CODES = { '0', '1', '2', '3', '4', '5', '6',
字符串函数模拟注册'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z' };
/**
* 获取随机字符串
*
* @param length
*            字符串的长度
* @return 一个指定长度的字符转
*/
public static String getRandCode(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++)
sb.append(Int(CODES.length)]);
String();
}
private int width;// 图片宽
private int height;// 图片高
public test(int width, int height) {
this.width = width;
this.height = height;
}
public BufferedImage getValidateCode(String code) {
int codeX = 0, codeY = 0, fontHeight = 0, lineCount = 0;
codeX = width / (code.length() +2);// 每个字符的宽度
codeY = height - 4;
fontHeight = height - 2;// 字体的高度
lineCount = (width + height) / 2;// 干扰线条数
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = ateGraphics();
g.setFont(new Font("宋体", Font.BOLD, fontHeight));// 随机字体
// 将图像填充为白
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 绘制干扰线
for (int i = 0; i < lineCount; i++) {
g.setColor(randColor());
int x = Int(width);
int y = Int(height);
g.drawLine(x, y, x + Int(width / 8),
y + Int(height / 8));
}
// 绘制字符
for (int i = 0; i < code.length(); i++) {
g.setColor(randColor());// 产生随机的颜值,让输出的每个字符的颜值都将不同。
g.drawString(code.substring(i, i + 1), (i + 1) * codeX, codeY);
}
g.dispose();
return buffImg;
}
public Color randColor() {
return new Int(255), Int(255),
}
public Font randFont(int size) {
Font[] fonts = LocalGraphicsEnvironment()
.getAllFonts();// 获取本体所有的字体
return Int(fonts.length)].deriveFont(size);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。