1. 程式人生 > >圖片驗證碼的方法

圖片驗證碼的方法

1.生成驗證碼的工具類

  1. package com.quanran.common.util;

  2. import java.awt.BasicStroke;

  3. import java.awt.Color;

  4. import java.awt.Font;

  5. import java.awt.Graphics2D;

  6. import java.awt.image.BufferedImage;

  7. import java.util.Random;

  8. /**

  9. * <p>Description: [生成驗證碼的控制類]</p>

  10. * Created on 2018年3月1日 下午5:52:58

  11. * @author <a href="mailto: [email protected]">全冉</a>

  12. * @version 1.0

  13. * Copyright (c) 2018 北京全冉科技有限公司

  14. */

  15. public class VerifyCodeUtils {

  16. /**

  17. * 圖片的寬度

  18. */

  19. private int w = 70;

  20. /**

  21. * 圖片的高度

  22. */

  23. private int h = 35;

  24. /**

  25. * 定義有那些字型

  26. */

  27. private String[] fontNames = { "宋體", "華文楷體", "黑體", "微軟雅黑", "楷體_GB2312" };

  28. /**

  29. * 定義有那些驗證碼的隨機字元

  30. */

  31. private String codes = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

  32. /**

  33. * 用於gettext 方法 獲得生成的驗證碼文字

  34. */

  35. private String text;

  36. /**

  37. * 隨機數物件

  38. */

  39. private Random r = new Random();

  40. /**

  41. * <p>Discription:[生成隨機顏色]</p>

  42. * Created on 2018年3月1日 下午5:56:19

  43. * @return Color 返回顏色類

  44. * @author:[全冉]

  45. */

  46. private Color randomColor() {

  47. int red = r.nextInt(150);

  48. int green = r.nextInt(150);

  49. int blue = r.nextInt(150);

  50. return new Color(red, green, blue);

  51. }

  52. /**

  53. * <p>Discription:[生成隨機字型]</p>

  54. * Created on 2018年3月1日 下午5:56:42

  55. * @return Font 返回字型類

  56. * @author:[全冉]

  57. */

  58. private Font randomFont() {

  59. int index = r.nextInt(fontNames.length);

  60. String fontName = fontNames[index];

  61. int style = r.nextInt(4);

  62. int size = r.nextInt(5) + 24;

  63. return new Font(fontName, style, size);

  64. }

  65. /**

  66. * <p>Discription:[畫干擾線]</p>

  67. * Created on 2018年3月1日 下午5:57:00

  68. * @param image 圖片

  69. * @author:[全冉]

  70. */

  71. private void drawLine(BufferedImage image) {

  72. // 干擾線的個數

  73. int num = 3;

  74. Graphics2D g2 = (Graphics2D) image.getGraphics();

  75. for (int i = 0; i < num; i++) {

  76. // (x1,y1)為干擾線的起始點

  77. int x1 = r.nextInt(w);

  78. int y1 = r.nextInt(h);

  79. // (x2,y2)為干擾線的結束點

  80. int x2 = r.nextInt(w);

  81. int y2 = r.nextInt(h);

  82. // 設定干擾線的寬度

  83. g2.setStroke(new BasicStroke(1.5F));

  84. // 干擾線的顏色

  85. g2.setColor(Color.blue);

  86. // 將當前這條幹擾線畫出來

  87. g2.drawLine(x1, y1, x2, y2);

  88. }

  89. }

  90. /**

  91. * <p>Discription:[得到codes的長度內的隨機數 並使用charAt 取得隨機數位置上的codes中的字元]</p>

  92. * Created on 2018年3月1日 下午5:58:25

  93. * @return char 返回隨機字元

  94. * @author:[全冉]

  95. */

  96. private char randomChar() {

  97. int index = r.nextInt(codes.length());

  98. return codes.charAt(index);

  99. }

  100. /**

  101. * <p>Discription:[建立一張驗證碼的圖片]</p>

  102. * Created on 2018年3月1日 下午6:00:42

  103. * @return BufferedImage 返回一張圖片

  104. * @author:[全冉]

  105. */

  106. public BufferedImage createImage() {

  107. // BufferedImage的構造(寬度,高度和圖片型別)

  108. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

  109. Graphics2D g2 = (Graphics2D) image.getGraphics();

  110. // 下面兩行程式碼是為了解決圖片背景色為黑色的問題,我設定成了白色

  111. g2.setColor(Color.white);

  112. g2.fillRect(0, 0, w, h);

  113. // 可變字串儲存圖片裡的文字

  114. StringBuilder sb = new StringBuilder();

  115. // 向圖中畫四個字元

  116. for (int i = 0; i < 4; i++) {

  117. String s = randomChar() + "";

  118. sb.append(s);

  119. float x = i * 1.0F * w / 4;

  120. g2.setFont(randomFont());

  121. g2.setColor(randomColor());

  122. g2.drawString(s, x, h - 5);

  123. }

  124. this.text = sb.toString();

  125. drawLine(image);

  126. // 返回圖片

  127. return image;

  128. }

  129. /**

  130. * <p>Discription:[得到驗證碼的文字]</p>

  131. * Created on 2018年3月1日 下午6:01:00

  132. * @return String 返回驗證碼文字

  133. * @author:[全冉]

  134. */

  135. public String getText() {

  136. return text;

  137. }

  138. }

2.呼叫工具類

  1. package com.quanran.invite.controller;

  2. import io.swagger.annotations.Api;

  3. import io.swagger.annotations.ApiImplicitParam;

  4. import io.swagger.annotations.ApiImplicitParams;

  5. import io.swagger.annotations.ApiOperation;

  6. import io.swagger.annotations.ApiParam;

  7. import java.awt.image.BufferedImage;

  8. import java.io.OutputStream;

  9. import javax.imageio.ImageIO;

  10. import javax.servlet.http.HttpServletRequest;

  11. import javax.servlet.http.HttpServletResponse;

  12. import org.springframework.web.bind.annotation.GetMapping;

  13. import org.springframework.web.bind.annotation.RequestMapping;

  14. import org.springframework.web.bind.annotation.RequestParam;

  15. import org.springframework.web.bind.annotation.RestController;

  16. import com.quanran.visitor.common.util.VerifyCodeUtils;

  17. /**

  18. * <p>Description: [invite系統裡的邀請碼重新發送介面]</p>

  19. * Created on 2017年11月16日 下午2:42:59

  20. * @author <a href="mailto: [email protected]">全冉</a>

  21. * @version 1.0

  22. * Copyright (c) 2017 北京全冉科技有限公司

  23. */

  24. @Api(value="invite系統裡的邀請碼重新發送介面", description="invite系統裡的邀請碼重新發送介面")

  25. @RestController

  26. @RequestMapping("/invitationCode")

  27. public class InvitationCodeController {

  28. @ApiOperation("簡訊重發的驗證碼介面")

  29. @GetMapping("getVerifyCode")

  30. @ApiImplicitParams({

  31. @ApiImplicitParam(name = "verifyCodeKey", value = "驗證碼的key", required = true, paramType = "query")

  32. })

  33. public void getVerifyCode(HttpServletRequest request, HttpServletResponse response,

  34. @ApiParam(value="驗證碼的key", required = true) @RequestParam String verifyCodeKey) {

  35. // 生成驗證碼的圖片

  36. VerifyCodeUtils code = new VerifyCodeUtils();

  37. BufferedImage image = code.createImage();

  38. // 設定響應頭通知瀏覽器以圖片的形式開啟

  39. response.setContentType("image/jpeg");

  40. // 設定響應頭控制瀏覽器不要快取

  41. response.setHeader("Pragma","no-cache");

  42. response.setHeader("Cache-Control","no-cache");

  43. response.setIntHeader("Expires",-1);

  44. // 將圖片變成流寫給瀏覽器

  45. OutputStream os=response.getOutputStream();

  46. ImageIO.write(image, "jpg", os);

  47. // 清空關閉流

  48. os.flush();

  49. os.close();

  50. os=null;

  51. response.flushBuffer();

  52. }

  53. }

備註:verifyCodeKey引數是前臺傳過來的時間戳,開發中,我們會將此時間戳當做key,生成的驗證碼內容當做value,存到redis中