java生成验证码

心已赠人 2022-07-13 06:52 297阅读 0赞

前端调用:

后台代码:

  1. private int w = 70;
  2. private int h = 26;
  3. /**
  4. * 生成验证码
  5. */
  6. @RequestMapping
  7. public void captcha(String width, String height, HttpServletResponse response, Model model)
  8. {
  9. OutputStream out = null;
  10. try
  11. {
  12. response.setHeader("Pragma", "no-cache");
  13. response.setHeader("Cache-Control", "no-cache");
  14. response.setDateHeader("Expires", 0);
  15. response.setContentType("image/jpeg");
  16. if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height))
  17. {
  18. w = NumberUtils.toInt(width);
  19. h = NumberUtils.toInt(height);
  20. }
  21. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  22. Graphics g = image.getGraphics();
  23. g.setColor(getRandColor(220, 250));// 生成背景
  24. g.fillRect(0, 0, w, h);
  25. for (int i = 0; i < 8; i++) // 加入干扰线条
  26. {
  27. g.setColor(getRandColor(40, 150));
  28. Random random = new Random();
  29. int x = random.nextInt(w);
  30. int y = random.nextInt(h);
  31. int x1 = random.nextInt(w);
  32. int y1 = random.nextInt(h);
  33. g.drawLine(x, y, x1, y1);
  34. }
  35. String s = createCharacter(g);// 生成字符
  36. SessionUtils.put(Constants.SESSION_KEY_CAPTCHA, s);
  37. g.dispose();
  38. out = response.getOutputStream();
  39. ImageIO.write(image, "JPEG", out);
  40. out.close();
  41. }
  42. catch (Exception e)
  43. {
  44. logger.error("Write Captcha Error", e);
  45. }
  46. finally
  47. {
  48. IOUtils.closeQuietly(out);
  49. }
  50. }
  51. private Color getRandColor(int fc, int bc)
  52. {
  53. int f = fc;
  54. int b = bc;
  55. Random random = new Random();
  56. if (f > 255)
  57. {
  58. f = 255;
  59. }
  60. if (b > 255)
  61. {
  62. b = 255;
  63. }
  64. return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
  65. }
  66. private String createCharacter(Graphics g)
  67. {
  68. char[] codeSeq =
  69. { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
  70. //字体:宋体, 新宋体, 黑体, 楷体, 隶书
  71. String[] fontTypes =
  72. { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
  73. Random random = new Random();
  74. StringBuilder s = new StringBuilder();
  75. for (int i = 0; i < 4; i++)
  76. {
  77. String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);
  78. g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
  79. g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD, 26));
  80. g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
  81. s.append(r);
  82. }
  83. return s.toString();
  84. }

发表评论

表情:
评论列表 (有 0 条评论,297人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java生成图片验证

    功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。 VerifyCodeUtils类,生成图片流,然后不同框