您的位置:首页 > Web前端

java开发_使用BufferedImage生成验证码

2013-07-24 09:27 477 查看
前台处理返回的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;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: