记录,备用
/**
* 已有验证码,生成验证码图片
*
* @param textCode 文本验证码
* @param width 图片宽度
* @param height 图片高度
* @param interLine 图片中干扰线的条数
* @param randomLocation 每个字符的高低位置是否随机
* @param backColor 图片颜色,若为null,则采用随机颜色
* @param foreColor 字体颜色,若为null,则采用随机颜色
* @param lineColor 干扰线颜色,若为null,则采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage getImageCode(String textCode, int width, int height, int interLine,
boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {
Random r = new Random();
BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bim.getGraphics();
// 画背景图
g.setColor(backColor == null ? getRandomColor() : backColor);
g.fillRect(0, 0, width, height);
// 画干扰线
//Random r = new Random();
if (interLine > 0) {
int x = 0, y = 0, x1 = width, y1 = 0;
for (int i = 0; i < interLine; i++) {
g.setColor(lineColor == null ? getRandomColor() : lineColor);
y = r.nextInt(height);
y1 = r.nextInt(height);
g.drawLine(x, y, x1, y1);
}
}
// 添加噪点
float yawpRate = 0.01f;
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = r.nextInt(width);
int y = r.nextInt(height);
bim.setRGB(x, y, r.nextInt(255));
}
// 写验证码
// 字体大小为图片高度的80%
int fCount = textCode.length();
int fsize = (int) (height * 0.7);
int fx = width / fCount;
int fy = fsize;
Font font = new Font("Fixedsys", Font.BOLD, fsize);
g.setFont(font);
// 写验证码字符
for (int i = 0; i < fCount; i++) {
// 每个字符高低是否随机
fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height) : fy;
g.setColor(foreColor == null ? getRandomColor() : foreColor);
g.drawString(textCode.charAt(i) + "", fx * i + (0 < i && i < fCount ? 3 : 0), fy);
}
g.dispose();
return bim;
}
/**
* 产生随机颜色
*
* @return
*/
private static Color getRandomColor() {
//Random r = new Random();
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
return c;
}