验证码

18 篇文章 0 订阅

public String viewIndentyingCode() throws IOException {
  Random random = new Random();
  StringBuffer codeBuffer = new StringBuffer();
  char randomCode;
  int width = 85;
  int height = 30;
  int fontWidth = 20;
  BufferedImage bim = new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
  Graphics2D g2d = (Graphics2D) bim.getGraphics();

  // set background color
  // g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR,0.0f));
  g2d.setColor(new Color(255, 255, 255));
  g2d.fillRect(0, 0, width, height);

  int size = width / fontWidth;
  Font font;
  int colorRandom;
  int styleRandom;

  // draw digit chinese font
  for (int i = 0; i < size; i++) {
   // randomCode=(char) (random.nextInt(26)+'A');
   randomCode = (char) (random.nextInt(9) + '0');
   styleRandom = random.nextInt(30);
   if (styleRandom % 3 == 0) {
    font = new Font("", Font.BOLD, 25 + (7 - random.nextInt(15)));
    colorRandom = random.nextInt(255);
    g2d.setColor(new Color(colorRandom, 255 - colorRandom,
      (int) ((colorRandom + 255) / 2)));
   } else if (styleRandom % 2 == 0) {
    font = new Font("", Font.ITALIC, 25 + (7 - random.nextInt(15)));
    colorRandom = random.nextInt(255);
    g2d.setColor(new Color(colorRandom,
      (int) ((colorRandom + 255) / 2), 255 - colorRandom));
   } else {
    font = new Font("", Font.TRUETYPE_FONT, 25 + (7 - random
      .nextInt(15)));
    colorRandom = random.nextInt(255);
    g2d.setColor(new Color((int) ((colorRandom + 255) / 2),
      colorRandom, 255 - colorRandom));
   }
   g2d.setFont(font);
   codeBuffer.append(randomCode);
   g2d.drawString(randomCode + "", new Double(fontWidth * (i + 0.25))
     .intValue()
     + 5 - random.nextInt(10), 25 + random.nextInt(10) - 5);
  }

  g2d.dispose();

  // write the code to session
  sessionService.setIndentifyingCode(codeBuffer.toString(), getSession());

  // response image stream
  HttpServletResponse response = getResponse();
  response.setContentType("image/jpeg");
  response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Pragma", "no-cache");
  response.setDateHeader("Expires", 0);
  ImageIO.write(bim, "jpeg", response.getOutputStream());
  return NONE;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值