javaweb项目登录注册界面验证码动态生成展示

港控/mmm° 2022-06-06 13:42 369阅读 0赞

前端html代码如下

  1. <img class="header-code" src="/validateCode" width="50" height="24">

对应后端controller接口如下

  1. /** * 获取验证码 * @param session * @param response */ @RequestMapping("validateCode")
  2. public void validateCode(HttpSession session, HttpServletRequest request, HttpServletResponse response){
  3. try {
  4. response.reset();
  5. // 设置响应的类型格式为图片格式
  6. response.setContentType("image/jpeg");
  7. //禁止图像缓存。
  8. response.setHeader("Pragma", "no-cache");
  9. response.setHeader("Cache-Control", "no-cache");
  10. response.setDateHeader("Expires", 0);
  11. String code = VerifyCodeUtils.generateVerifyCode(4);
  12. session.setMaxInactiveInterval(60*60*3);
  13. session.setAttribute("code", code);
  14. VerifyCodeUtils.outputImage(200,80,response.getOutputStream(),code);
  15. response.flushBuffer();
  16. } catch (Exception e) {
  17. logger.error("出现异常! 操作失败! 异常信息: " + e.getMessage());
  18. }
  19. }

使用utils如下

  1. package com.ig.common.util;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.Graphics2D;
  6. import java.awt.RenderingHints;
  7. import java.awt.geom.AffineTransform;
  8. import java.awt.image.BufferedImage;
  9. import java.io.File;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.OutputStream;
  13. import java.util.Arrays;
  14. import java.util.Random;
  15. import javax.imageio.ImageIO;
  16. public class VerifyCodeUtils{
  17. //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
  18. public static final String VERIFY_CODES = "23456789";
  19. private static Random random = new Random();
  20. /** * 使用系统默认字符源生成验证码 * @param verifySize 验证码长度 * @return */ public static String generateVerifyCode(int verifySize){
  21. return generateVerifyCode(verifySize, VERIFY_CODES);
  22. }
  23. /** * 使用指定源生成验证码 * @param verifySize 验证码长度 * @param sources 验证码字符源 * @return */ public static String generateVerifyCode(int verifySize, String sources){
  24. if(sources == null || sources.length() == 0){
  25. sources = VERIFY_CODES;
  26. }
  27. int codesLen = sources.length();
  28. Random rand = new Random(System.currentTimeMillis());
  29. StringBuilder verifyCode = new StringBuilder(verifySize);
  30. for(int i = 0; i < verifySize; i++){
  31. verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
  32. }
  33. return verifyCode.toString();
  34. }
  35. /** * 生成随机验证码文件,并返回验证码值 * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
  36. String verifyCode = generateVerifyCode(verifySize);
  37. outputImage(w, h, outputFile, verifyCode);
  38. return verifyCode;
  39. }
  40. /** * 输出随机验证码图片流,并返回验证码值 * @param w * @param h * @param os * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
  41. String verifyCode = generateVerifyCode(verifySize);
  42. outputImage(w, h, os, verifyCode);
  43. return verifyCode;
  44. }
  45. /** * 生成指定验证码图像文件 * @param w * @param h * @param outputFile * @param code * @throws IOException */ public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
  46. if(outputFile == null){
  47. return;
  48. }
  49. File dir = outputFile.getParentFile();
  50. if(!dir.exists()){
  51. dir.mkdirs();
  52. }
  53. try{
  54. outputFile.createNewFile();
  55. FileOutputStream fos = new FileOutputStream(outputFile);
  56. outputImage(w, h, fos, code);
  57. fos.close();
  58. } catch(IOException e){
  59. throw e;
  60. }
  61. }
  62. /** * 输出指定验证码图片流 * @param w * @param h * @param os * @param code * @throws IOException */ public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
  63. int verifySize = code.length();
  64. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  65. Random rand = new Random();
  66. Graphics2D g2 = image.createGraphics();
  67. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  68. Color[] colors = new Color[5];
  69. Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
  70. Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
  71. Color.PINK, Color.YELLOW };
  72. float[] fractions = new float[colors.length];
  73. for(int i = 0; i < colors.length; i++){
  74. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  75. fractions[i] = rand.nextFloat();
  76. }
  77. Arrays.sort(fractions);
  78. g2.setColor(Color.GRAY);// 设置边框色
  79. g2.fillRect(0, 0, w, h);
  80. Color c = getRandColor(200, 250);
  81. g2.setColor(c);// 设置背景色
  82. g2.fillRect(0, 2, w, h-4);
  83. //绘制干扰线
  84. Random random = new Random();
  85. g2.setColor(getRandColor(160, 200));// 设置线条的颜色
  86. for (int i = 0; i < 20; i++) {
  87. int x = random.nextInt(w - 1);
  88. int y = random.nextInt(h - 1);
  89. int xl = random.nextInt(6) + 1;
  90. int yl = random.nextInt(12) + 1;
  91. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  92. }
  93. // 添加噪点
  94. float yawpRate = 0.05f;// 噪声率
  95. int area = (int) (yawpRate * w * h);
  96. for (int i = 0; i < area; i++) {
  97. int x = random.nextInt(w);
  98. int y = random.nextInt(h);
  99. int rgb = getRandomIntColor();
  100. image.setRGB(x, y, rgb);
  101. }
  102. shear(g2, w, h, c);// 使图片扭曲
  103. g2.setColor(getRandColor(100, 160));
  104. int fontSize = h-4;
  105. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  106. g2.setFont(font);
  107. char[] chars = code.toCharArray();
  108. for(int i = 0; i < verifySize; i++){
  109. AffineTransform affine = new AffineTransform();
  110. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
  111. g2.setTransform(affine);
  112. g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
  113. }
  114. g2.dispose();
  115. ImageIO.write(image, "jpg", os);
  116. //注意看以下几句的使用
  117. os.flush();
  118. os.close();
  119. os=null;
  120. }
  121. private static Color getRandColor(int fc, int bc) {
  122. if (fc > 255)
  123. fc = 255;
  124. if (bc > 255)
  125. bc = 255;
  126. int r = fc + random.nextInt(bc - fc);
  127. int g = fc + random.nextInt(bc - fc);
  128. int b = fc + random.nextInt(bc - fc);
  129. return new Color(r, g, b);
  130. }
  131. private static int getRandomIntColor() {
  132. int[] rgb = getRandomRgb();
  133. int color = 0;
  134. for (int c : rgb) {
  135. color = color << 8;
  136. color = color | c;
  137. }
  138. return color;
  139. }
  140. private static int[] getRandomRgb() {
  141. int[] rgb = new int[3];
  142. for (int i = 0; i < 3; i++) {
  143. rgb[i] = random.nextInt(255);
  144. }
  145. return rgb;
  146. }
  147. private static void shear(Graphics g, int w1, int h1, Color color) {
  148. shearX(g, w1, h1, color);
  149. shearY(g, w1, h1, color);
  150. }
  151. private static void shearX(Graphics g, int w1, int h1, Color color) {
  152. int period = random.nextInt(2);
  153. boolean borderGap = true;
  154. int frames = 1;
  155. int phase = random.nextInt(2);
  156. for (int i = 0; i < h1; i++) {
  157. double d = (double) (period >> 1)
  158. * Math.sin((double) i / (double) period
  159. + (6.2831853071795862D * (double) phase)
  160. / (double) frames);
  161. g.copyArea(0, i, w1, 1, (int) d, 0);
  162. if (borderGap) {
  163. g.setColor(color);
  164. g.drawLine((int) d, i, 0, i);
  165. g.drawLine((int) d + w1, i, w1, i);
  166. }
  167. }
  168. }
  169. private static void shearY(Graphics g, int w1, int h1, Color color) {
  170. int period = random.nextInt(40) + 10; // 50;
  171. boolean borderGap = true;
  172. int frames = 20;
  173. int phase = 7;
  174. for (int i = 0; i < w1; i++) {
  175. double d = (double) (period >> 1)
  176. * Math.sin((double) i / (double) period
  177. + (6.2831853071795862D * (double) phase)
  178. / (double) frames);
  179. g.copyArea(i, 0, 1, h1, 0, (int) d);
  180. if (borderGap) {
  181. g.setColor(color);
  182. g.drawLine(i, (int) d, i, 0);
  183. g.drawLine(i, (int) d + h1, i, h1);
  184. }
  185. }
  186. }

发表评论

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

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

相关阅读