public static final char[] CHARS = { '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', };
public static Random random = new Random();
/**生成一串随即字符
* @return返回字符串String
*/
public static String getRandomString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 4; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}
/**生成随即颜色
* @return返回颜色对象Color
*/
public static Color getRandomColor() {
// return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
return new Color(220,220,220);
}
public static Color getReverseColor(Color c) {
return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
}
/**
* 得到随机颜色
* @param fc
* @param bc
* @return
*/
private static Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**页面获得随机码的方法,生成随机验证码-4位
* @param request* @param response
* @throws IOException
*/
public void getRandomImg(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.setContentType("image/jpeg");
String radomString = getRandomString();
request.removeAttribute("radomString");
request.getSession(true).setAttribute("radomString", radomString);
Color color = getRandomColor();
Color reverse = getReverseColor(color);
BufferedImage bi = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,18));
//g.setColor(color);
g.fillRect(0,0,100,30);
g.setColor(reverse);
g.drawString(radomString,14,18);
// for (int i = 0,n = random.nextInt(100); i<n; i++) {
// g.drawRect(random.nextInt(100), random.nextInt(30), 1, 1);
// }
//背景干扰线
for (int i = 0; i < 3; i++) {
int x = random.nextInt(100);
int y = random.nextInt(30);
int xl = random.nextInt(100);
int yl = random.nextInt(100);
g.setColor(reverse);
g.drawLine(x, y, x + xl, y + yl);
}
ServletOutputStream out = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(bi);
out.flush();
}