Java验证码生成函数

来源:互联网 发布:分时博弈指标源码 编辑:程序博客网 时间:2024/05/21 22:32
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();                //将生成的随机数字符串写入memcachedCommonSessionFactory.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();}

0 0
原创粉丝点击