java生成图片验证码(字母 | 运算 | 汉字)

逃离我推掉我的手 2022-05-03 00:58 283阅读 0赞

java生成图片验证码(字母|运算|汉字)

1.先看下以下效果图,ui请勿参考

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pbmcxOTk1MTIyNA_size_27_color_FFFFFF_t_70watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pbmcxOTk1MTIyNA_size_27_color_FFFFFF_t_70 1watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pbmcxOTk1MTIyNA_size_27_color_FFFFFF_t_70 2

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pbmcxOTk1MTIyNA_size_27_color_FFFFFF_t_70 3watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pbmcxOTk1MTIyNA_size_27_color_FFFFFF_t_70 4

2.后台工具类代码

  1. package com.ljm.verification.util;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.image.BufferedImage;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpSession;
  11. /**
  12. * @author lijunming
  13. * @date 2018/10/26 2:57 PM
  14. */
  15. public class RandomValidateCode {
  16. private static int width = 135;// 图片宽
  17. private static int height = 28;// 图片高
  18. private static int lineSize = 40;// 干扰线数量
  19. private static Random random = new Random();
  20. /**
  21. * 设置验证码字体
  22. *
  23. * @return 字体
  24. */
  25. private static Font getFont() {
  26. return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
  27. }
  28. /**
  29. * 设置验证码颜色
  30. *
  31. * @param fc
  32. * @param bc
  33. * @return rgb值
  34. */
  35. private static Color getRandColor(int fc, int bc) {
  36. if (fc > 255)
  37. fc = 255;
  38. if (bc > 255)
  39. bc = 255;
  40. int r = fc + random.nextInt(bc - fc - 16);
  41. int g = fc + random.nextInt(bc - fc - 14);
  42. int b = fc + random.nextInt(bc - fc - 18);
  43. return new Color(r, g, b);
  44. }
  45. /**
  46. * 生成随机验证码,绘制成图片,并且写入结果
  47. *
  48. * @param request
  49. * @param response
  50. */
  51. public static void getRandcode(HttpServletRequest request,
  52. HttpServletResponse response) {
  53. HttpSession session = request.getSession();
  54. // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
  55. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  56. Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
  57. g.fillRect(0, 0, width, height);
  58. g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 45)); //图片上字的大小
  59. g.setColor(getRandColor(110, 133));
  60. // 绘制干扰线
  61. for (int i = 0; i <= lineSize; i++) {
  62. drowLine(g);
  63. }
  64. // 绘制随机验证吗
  65. String randomString = getValidate();
  66. //把生成的验证码存入session,并且1分钟超时失效
  67. session.setAttribute("verification", result);
  68. session.setMaxInactiveInterval(60);
  69. String[] arr = randomString.toString().split("");
  70. for (int i = 1; i <= arr.length; i++) {
  71. drowString(g, arr[i - 1], i);
  72. }
  73. g.dispose();
  74. try {
  75. // 将内存中的图片通过流动形式输出到客户端
  76. ImageIO.write(image, "JPEG", response.getOutputStream());
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. /**
  82. * 绘制图片
  83. */
  84. private static String drowString(Graphics g, String randomString, int i) {
  85. int j = 15;
  86. if (result instanceof Integer) {
  87. j = 11;
  88. }
  89. g.setFont(getFont());
  90. g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
  91. .nextInt(121)));
  92. g.translate(random.nextInt(3), random.nextInt(3));
  93. g.translate(random.nextInt(3), random.nextInt(3));
  94. g.drawString(randomString, j * i, 12);
  95. return randomString;
  96. }
  97. /**
  98. * 绘制干扰线
  99. */
  100. private static void drowLine(Graphics g) {
  101. int x = random.nextInt(width);
  102. int y = random.nextInt(height);
  103. int xl = random.nextInt(13);
  104. int yl = random.nextInt(15);
  105. g.drawLine(x, y, x + xl, y + yl);
  106. }
  107. public static Object result;
  108. /**
  109. * 生成字母验证码
  110. * @return 验证码的内容
  111. */
  112. public static String createAB() {
  113. String[] abc = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "q", "r", "s", "t", "u", "v", "o", "p", "w", "x", "z", "y", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "Q", "R", "S", "T", "U", "V", "O", "P", "W", "X", "Y", "Z"};
  114. Random rd = new Random();
  115. int index = rd.nextInt(abc.length);
  116. String one = abc[index];
  117. index = rd.nextInt(abc.length);
  118. String two = abc[index];
  119. index = rd.nextInt(abc.length);
  120. String three = abc[index];
  121. index = rd.nextInt(abc.length);
  122. String four = abc[index];
  123. result = one + two + three + four;
  124. String str = one + two + three + four;
  125. return str;
  126. }
  127. /**
  128. * 生成加减乘除算法验证码
  129. * 由于2位数的 乘除对某些人算起来麻烦
  130. * 有兴趣的可以扩展乘法和除法
  131. * @return 验证码的内容
  132. */
  133. public static String createNumber() {
  134. String fu[] = new String[]{"+", "-", "*", "/"};
  135. Random rd = new Random();
  136. int i = rd.nextInt(2);
  137. int num1 = rd.nextInt(100);
  138. int num2 = rd.nextInt(100);
  139. if (i == 0) {
  140. result = num1 + num2;
  141. } else {
  142. //循环保证永远不会出现减法结果是负数
  143. while (num1 < num2) {
  144. num1 = rd.nextInt(100);
  145. }
  146. result = num1 - num2;
  147. }
  148. String str = num1 + fu[i] + num2 + "=";
  149. return str;
  150. }
  151. /**
  152. * 生产汉字验证吗
  153. * @return 验证码的内容
  154. */
  155. public static String createChinese() {
  156. String chinese[] = new String[]{
  157. "勿", "忘", "初", "心", "方", "得", "始", "终", "认", "真", "切", "怂", "从", "一", "而", "终", "英", "雄", "联", "盟"
  158. };
  159. Random rd = new Random();
  160. int index = rd.nextInt(chinese.length);
  161. String one = chinese[index];
  162. index = rd.nextInt(chinese.length);
  163. String two = chinese[index];
  164. index = rd.nextInt(chinese.length);
  165. String three = chinese[index];
  166. index = rd.nextInt(chinese.length);
  167. String four = chinese[index];
  168. result = one + two + three + four;
  169. String str = one + two + three + four;
  170. return str;
  171. }
  172. /**
  173. * 随机调用验证码
  174. */
  175. public static String getValidate() {
  176. Random rd = new Random();
  177. int i = rd.nextInt(4);
  178. if (i == 1) {
  179. return createAB();
  180. } else if (i == 2) {
  181. return createChinese();
  182. }
  183. return createNumber();
  184. }
  185. }

3.Controller

  1. package com.ljm.verification.controller;
  2. import com.ljm.verification.util.RandomValidateCode;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.*;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import javax.servlet.http.HttpSession;
  8. /**
  9. * @author lijunming
  10. * @date 2018/10/26 3:57 PM
  11. */
  12. @Controller
  13. public class TestController {
  14. /*
  15. * 去登陆页面
  16. */
  17. @GetMapping("/login")
  18. public String toLogin(){
  19. return "login";
  20. }
  21. /*
  22. * 登录页面生成验证码
  23. */
  24. @RequestMapping(value = "/getVerify.htm")
  25. public void getVerify(HttpServletRequest request, HttpServletResponse response){
  26. response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
  27. response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
  28. response.setHeader("Cache-Control", "no-cache");
  29. response.setDateHeader("Expire", 0);
  30. try {
  31. RandomValidateCode.getRandcode(request, response);//输出验证码图片方法
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. /*
  37. * 验证输入的验证码是否正确
  38. */
  39. @RequestMapping("/checkValidate")
  40. @ResponseBody
  41. public String checkValidate(@RequestParam("verification")Object yzm, HttpSession session) throws Exception{
  42. Object result=session.getAttribute("verification");
  43. //验证码只有1分钟的有效期,超时返回-1
  44. if(session.getAttribute("verification")==null){
  45. return "-1";
  46. }
  47. //如果为字母验证码或者 1表示通告,0表示验证失败
  48. if(result instanceof String){
  49. if(yzm.toString().toUpperCase().equals(result.toString().toUpperCase())){
  50. return "1";
  51. }
  52. return "0";
  53. //如果为数字验证码
  54. }else{
  55. if(result.toString().equals(yzm)){
  56. return "1";
  57. }
  58. }
  59. return "0";
  60. }
  61. }

4.前台页面

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style type="text/css">
  7. div{
  8. text-align: center;
  9. }
  10. form{
  11. margin-top:10%;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div >
  17. <form action="login"method="post">
  18. <div id="error"></div>
  19. 账号:<input type="text" name="userName"/><br/>
  20. 密码:<input type="password" name="password" /><br/>
  21. <img id="yzm" src="getVerify.htm"/> <a href="javascript:replace()">换一张</a><br/>
  22. 验证码<input type="text" name="yzm"/>
  23. <input type="button" value="登陆" id="login"/>
  24. </form>
  25. </div>
  26. </body>
  27. <script type="text/javascript" src="jquery-1.8.0.js"></script>
  28. <script type="text/javascript">
  29. function replace(){
  30. $("#yzm").attr("src","getVerify.htm?t="+ Math.random());
  31. }
  32. $(function(){
  33. $("#login").click(function(){
  34. var flags=false;
  35. var verification=$("[name='yzm']").val();
  36. $.ajax({
  37. url:"checkValidate",
  38. async:false,
  39. type:"get",
  40. data:{"verification":verification},
  41. dataType:"text",
  42. success:function(flag){
  43. if(flag=="-1"){
  44. $("#error").html("验证码已超时,请换个","red");
  45. flags=true;
  46. }else if (flag=="0"){
  47. $("#error").html("验证码错误").css("color","red");
  48. flags=true;
  49. }else{
  50. $("#error").html("登陆成功").css("color","green");
  51. }
  52. }
  53. });
  54. //如果验证失败则不进后面的登陆
  55. if(flags){
  56. return;
  57. }
  58. });
  59. })
  60. </script>
  61. </html>

5.由于小项目,没有用github

百度云下载:https://pan.baidu.com/s/12EwH84ObKKEC0h_n_qssOA 密码:6rtq

发表评论

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

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

相关阅读

    相关 Java生成图片验证

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