前台处理返回的ByteArrayOutputStream
//获取验证码写入ByteArrayOutputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
String rand = this.getValidateImage(RANGE, 70, 21, 4, 1, os);
req.getSession().setAttribute(KEY, rand);
return new ByteArrayInputStream(os.toByteArray());
} finally {
if (os != null) os.close();
}
//生成验证码方法
public static String getValidateImage(String str, int width, int height, int show, int lineNum, OutputStream output)
{Random random = new Random();
BufferedImage image = new BufferedImage(width, height, 5);
Font font = new Font("Arial", 0, height - 1);
int distance = 18;
Graphics2D d = (Graphics2D)image.getGraphics();
d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
d.setColor(new Color(0X8FB9EB));
d.fillRect(0, 0, image.getWidth(), image.getHeight());
d.setColor(new Color(random.nextInt(100) + 100, random.nextInt(100) + 100, random.nextInt(100) + 100));
for (int i = 0; i < lineNum; i++) {
d.drawLine(random.nextInt(image.getWidth()), random.nextInt(image.getHeight()), random.nextInt(image.getWidth()),
random.nextInt(image.getHeight()));
}
d.setColor(new Color(0X8FB9EB));
d.setFont(font);
String checkCode = "";
int x = -distance;
for (int i = 0; i < show; i++) {
char tmp = str.charAt(random.nextInt(str.length()));
checkCode = checkCode + tmp;
x += distance;
d.setColor(new Color(random.nextInt(100) + 50, random.nextInt(100) + 50, random.nextInt(100) + 50));
d.drawString(String.valueOf(tmp), x, random.nextInt(image.getHeight() - font.getSize()) + font.getSize());
}
d.dispose();
try {
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
//logger.warn("生成验证码错误.", e);
}
return checkCode;
}