public void imageSecurityCode(){
char[] chars = {'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'};
//定义图片的宽度以及高度
int width = 161;
int height = 50;
//创建一个图片对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//得到图片对象的环境对象
Graphics g = image.createGraphics();
Random random = new Random();
//用随机颜色填充图像背景
g.setColor(new Color(239,239,239));
g.fillRect(0, 0, width, height);
//设置字体,下面准备画随机数
g.setFont(new Font("", Font.PLAIN, 40));
//随机字符串
StringBuilder rand = new StringBuilder();
for(int i = 0; i < 5; i++){
//生成六个随机字符
String str = String.valueOf(chars[random.nextInt(61)]);
rand.append(str);
g.setColor(new Color(20 + random.nextInt(80), 20 + random.nextInt(100), 20 + random.nextInt(90)));
//将随机字符画在图像上
g.drawString(str, (27 + random.nextInt(3)) * i + 8, 40);
//生成干扰线
for(int j = 0; j < 12; j++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(9);
int y1 = random.nextInt(9);
g.drawLine(x, y, x + x1, y + y1);
}
}
//使图片生效
g.dispose();
//将生成的随机数字符串写入memcached
CommonSessionFactory.getCommonSession(request, response).setAttribute(CacheConstant.DM_SECURITY_CODE, rand.toString());
//首先设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//输出图片到页面
try {
ImageIO.write(image, "jpg", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
Java验证码生成函数
最新推荐文章于 2023-12-28 14:04:20 发布