很久没写博客了,都快忘记这里有账号了。好了,不罗嗦,跟大家分享下生成验证码图片代码
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
public class ValidateCode {
/**
* 验证码属性名称
*/
public static final String VALIDATE_CODE_NAME = "validate_code";
char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/**
* 验证码图片的宽度。
*/
private int width = 75;
/**
* 验证码图片的高度。
*/
private int height = 20;
/**
* 验证码字符个数
*/
private int codeCount = 4;
/**
* xx
*/
private int xx = 0;
/**
* 字体高度
*/
private int fontHeight;
/**
* codeY
*/
private int codeY;
public ValidateCode() {
xx = width / (codeCount + 1);
fontHeight = height - 2;
codeY = height - 4;
}
public void getValidateImage() {
// 定义图像buffer
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D gd = buffImg.createGraphics();
// 创建一个随机数生成器类
Random random = new Random();
// 将图像填充为白色
gd.setColor(Color.WHITE);
gd.fillRect(0, 0, width, height);
// 创建字体,字体的大小应该根据图片的高度来定。
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
// 设置字体。
gd.setFont(font);
// 画边框。
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
// 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
gd.setColor(Color.BLACK);
for (int i = 0; i < 10; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
gd.drawLine(x, y, x + xl, y + yl);
}
// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// 随机产生codeCount数字的验证码。
for (int i = 0; i < 4; i++) {
// 得到随机产生的验证码数字。
String strRand = String.valueOf(codeSequence[random.nextInt(10)]);
// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不
同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用随机产生的颜色将验证码绘制到图像中。
gd.setColor(new Color(red, green, blue));
gd.drawString(strRand, (i + 1) * xx, codeY);
// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
try {
FileImageOutputStream writeImage = new FileImageOutputStream(new
File(
"c:\\pic.jpg"));
ImageIO.write(buffImg, "jpeg", writeImage);
writeImage.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ValidateCode vc = new ValidateCode();
vc.getValidateImage();
}
}