VerifyCodeUtils.java 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package com.goafanti.common.utils;
  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. import com.goafanti.core.shiro.token.TokenManager;
  17. public class VerifyCodeUtils {
  18. // 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
  19. public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  20. // 验证码的Key
  21. public static final String V_CODE = "_CODE";
  22. // 手机验证码
  23. public static final String M_VERIFY_CODES = "23456789";
  24. // 手机验证码Key
  25. public static final String M_CODE = "M_CODE";
  26. // 手机验证码生成时间
  27. public static final String M_CODE_TIME = "M_CODE_TIME";
  28. public static final String RESET_CODE = "RESET_CODE";
  29. public static final String RESET_CODE_TIME = "RESET_CODE_TIME";
  30. private static Random random = new Random();
  31. /**
  32. * 验证码对象
  33. *
  34. */
  35. public static class Verify {
  36. private String code; // 如 1 + 2
  37. private Integer value; // 如 3
  38. public String getCode() {
  39. return code;
  40. }
  41. public void setCode(String code) {
  42. this.code = code;
  43. }
  44. public Integer getValue() {
  45. return value;
  46. }
  47. public void setValue(Integer value) {
  48. this.value = value;
  49. }
  50. }
  51. /**
  52. * 使用系统默认字符源生成验证码
  53. *
  54. * @param verifySize
  55. * 验证码长度
  56. * @return
  57. */
  58. public static Verify generateVerify() {
  59. int number1 = new Random().nextInt(10) + 1;
  60. int number2 = new Random().nextInt(10) + 1;
  61. Verify entity = new Verify();
  62. entity.setCode(number1 + " x " + number2);
  63. entity.setValue(number1 + number2);
  64. return entity;
  65. }
  66. /**
  67. * 使用系统默认字符源生成验证码
  68. *
  69. * @param verifySize
  70. * 验证码长度
  71. * @return
  72. */
  73. public static String generateVerifyCode(int verifySize) {
  74. return generateVerifyCode(verifySize, VERIFY_CODES);
  75. }
  76. /**
  77. * 手机验证码
  78. *
  79. * @param verifySize
  80. * @return
  81. */
  82. public static String generateMobileVerifyCode(int verifySize) {
  83. return generateMobileVerifyCode(verifySize, M_VERIFY_CODES);
  84. }
  85. private static String generateMobileVerifyCode(int verifySize, String sources) {
  86. if (sources == null || sources.length() == 0) {
  87. sources = M_VERIFY_CODES;
  88. }
  89. int codesLen = sources.length();
  90. Random rand = new Random(System.currentTimeMillis());
  91. StringBuilder verifyCode = new StringBuilder(verifySize);
  92. for (int i = 0; i < verifySize; i++) {
  93. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
  94. }
  95. return verifyCode.toString();
  96. }
  97. /**
  98. * 清除验证码
  99. */
  100. public static void clearVerifyCode() {
  101. TokenManager.getSession().removeAttribute(V_CODE);
  102. }
  103. /**
  104. * 清除手机验证码
  105. */
  106. public static void clearMobileCode(){
  107. TokenManager.getSession().removeAttribute(M_CODE);
  108. }
  109. public static void clearMobileCodeTime(){
  110. TokenManager.getSession().removeAttribute(VerifyCodeUtils.M_CODE_TIME);
  111. }
  112. public static void clearResetCode(){
  113. TokenManager.getSession().removeAttribute(VerifyCodeUtils.RESET_CODE);
  114. }
  115. public static void clearResetCodeTime(){
  116. TokenManager.getSession().removeAttribute(VerifyCodeUtils.RESET_CODE_TIME);
  117. }
  118. /**
  119. * 对比验证码
  120. */
  121. public static boolean verifyCode(String code) {
  122. String v = (String) TokenManager.getVal2Session(V_CODE);
  123. return StringUtils.equals(v, StringUtils.lowerCase(code));
  124. }
  125. /**
  126. * 使用指定源生成验证码
  127. *
  128. * @param verifySize
  129. * 验证码长度
  130. * @param sources
  131. * 验证码字符源
  132. * @return
  133. */
  134. public static String generateVerifyCode(int verifySize, String sources) {
  135. if (sources == null || sources.length() == 0) {
  136. sources = VERIFY_CODES;
  137. }
  138. int codesLen = sources.length();
  139. Random rand = new Random(System.currentTimeMillis());
  140. StringBuilder verifyCode = new StringBuilder(verifySize);
  141. for (int i = 0; i < verifySize; i++) {
  142. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
  143. }
  144. return verifyCode.toString();
  145. }
  146. /**
  147. * 生成随机验证码文件,并返回验证码值
  148. *
  149. * @param w
  150. * @param h
  151. * @param outputFile
  152. * @param verifySize
  153. * @return
  154. * @throws IOException
  155. */
  156. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
  157. String verifyCode = generateVerifyCode(verifySize);
  158. outputImage(w, h, outputFile, verifyCode);
  159. return verifyCode;
  160. }
  161. /**
  162. * 输出随机验证码图片流,并返回验证码值
  163. *
  164. * @param w
  165. * @param h
  166. * @param os
  167. * @param verifySize
  168. * @return
  169. * @throws IOException
  170. */
  171. public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
  172. String verifyCode = generateVerifyCode(verifySize);
  173. outputImage(w, h, os, verifyCode);
  174. return verifyCode;
  175. }
  176. /**
  177. * 生成指定验证码图像文件
  178. *
  179. * @param w
  180. * @param h
  181. * @param outputFile
  182. * @param code
  183. * @throws IOException
  184. */
  185. public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
  186. if (outputFile == null) {
  187. return;
  188. }
  189. File dir = outputFile.getParentFile();
  190. if (!dir.exists()) {
  191. dir.mkdirs();
  192. }
  193. try {
  194. outputFile.createNewFile();
  195. FileOutputStream fos = new FileOutputStream(outputFile);
  196. outputImage(w, h, fos, code);
  197. fos.close();
  198. } catch (IOException e) {
  199. throw e;
  200. }
  201. }
  202. /**
  203. * 输出指定验证码图片流
  204. *
  205. * @param w
  206. * @param h
  207. * @param os
  208. * @param code
  209. * @throws IOException
  210. */
  211. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
  212. int verifySize = code.length();
  213. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  214. Random rand = new Random();
  215. Graphics2D g2 = image.createGraphics();
  216. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  217. Color[] colors = new Color[5];
  218. Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
  219. Color.ORANGE, Color.PINK, Color.YELLOW };
  220. float[] fractions = new float[colors.length];
  221. for (int i = 0; i < colors.length; i++) {
  222. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  223. fractions[i] = rand.nextFloat();
  224. }
  225. Arrays.sort(fractions);
  226. g2.setColor(Color.GRAY);// 设置边框色
  227. g2.fillRect(0, 0, w, h);
  228. Color c = getRandColor(200, 250);
  229. g2.setColor(c);// 设置背景色
  230. g2.fillRect(0, 2, w, h - 4);
  231. // 绘制干扰线
  232. Random random = new Random();
  233. g2.setColor(getRandColor(160, 200));// 设置线条的颜色
  234. for (int i = 0; i < 20; i++) {
  235. int x = random.nextInt(w - 1);
  236. int y = random.nextInt(h - 1);
  237. int xl = random.nextInt(6) + 1;
  238. int yl = random.nextInt(12) + 1;
  239. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  240. }
  241. // 添加噪点
  242. float yawpRate = 0.05f;// 噪声率
  243. int area = (int) (yawpRate * w * h);
  244. for (int i = 0; i < area; i++) {
  245. int x = random.nextInt(w);
  246. int y = random.nextInt(h);
  247. int rgb = getRandomIntColor();
  248. image.setRGB(x, y, rgb);
  249. }
  250. shear(g2, w, h, c);// 使图片扭曲
  251. g2.setColor(getRandColor(100, 160));
  252. int fontSize = h - 4;
  253. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  254. g2.setFont(font);
  255. char[] chars = code.toCharArray();
  256. for (int i = 0; i < verifySize; i++) {
  257. AffineTransform affine = new AffineTransform();
  258. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
  259. (w / verifySize) * i + fontSize / 2, h / 2);
  260. g2.setTransform(affine);
  261. g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
  262. }
  263. g2.dispose();
  264. ImageIO.write(image, "jpg", os);
  265. }
  266. private static Color getRandColor(int fc, int bc) {
  267. if (fc > 255)
  268. fc = 255;
  269. if (bc > 255)
  270. bc = 255;
  271. int r = fc + random.nextInt(bc - fc);
  272. int g = fc + random.nextInt(bc - fc);
  273. int b = fc + random.nextInt(bc - fc);
  274. return new Color(r, g, b);
  275. }
  276. private static int getRandomIntColor() {
  277. int[] rgb = getRandomRgb();
  278. int color = 0;
  279. for (int c : rgb) {
  280. color = color << 8;
  281. color = color | c;
  282. }
  283. return color;
  284. }
  285. private static int[] getRandomRgb() {
  286. int[] rgb = new int[3];
  287. for (int i = 0; i < 3; i++) {
  288. rgb[i] = random.nextInt(255);
  289. }
  290. return rgb;
  291. }
  292. private static void shear(Graphics g, int w1, int h1, Color color) {
  293. shearX(g, w1, h1, color);
  294. shearY(g, w1, h1, color);
  295. }
  296. private static void shearX(Graphics g, int w1, int h1, Color color) {
  297. int period = random.nextInt(2);
  298. boolean borderGap = true;
  299. int frames = 1;
  300. int phase = random.nextInt(2);
  301. for (int i = 0; i < h1; i++) {
  302. double d = (double) (period >> 1)
  303. * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
  304. g.copyArea(0, i, w1, 1, (int) d, 0);
  305. if (borderGap) {
  306. g.setColor(color);
  307. g.drawLine((int) d, i, 0, i);
  308. g.drawLine((int) d + w1, i, w1, i);
  309. }
  310. }
  311. }
  312. private static void shearY(Graphics g, int w1, int h1, Color color) {
  313. int period = random.nextInt(40) + 10; // 50;
  314. boolean borderGap = true;
  315. int frames = 20;
  316. int phase = 7;
  317. for (int i = 0; i < w1; i++) {
  318. double d = (double) (period >> 1)
  319. * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
  320. g.copyArea(i, 0, 1, h1, 0, (int) d);
  321. if (borderGap) {
  322. g.setColor(color);
  323. g.drawLine(i, (int) d, i, 0);
  324. g.drawLine(i, (int) d + h1, i, h1);
  325. }
  326. }
  327. }
  328. }