VerifyCodeUtils.java 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. * @param verifySize
  79. * @return
  80. */
  81. public static String generateMobileVerifyCode(int verifySize) {
  82. return generateMobileVerifyCode(verifySize, M_VERIFY_CODES);
  83. }
  84. private static String generateMobileVerifyCode(int verifySize, String sources) {
  85. if (sources == null || sources.length() == 0) {
  86. sources = M_VERIFY_CODES;
  87. }
  88. int codesLen = sources.length();
  89. Random rand = new Random(System.currentTimeMillis());
  90. StringBuilder verifyCode = new StringBuilder(verifySize);
  91. for (int i = 0; i < verifySize; i++) {
  92. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
  93. }
  94. return verifyCode.toString();
  95. }
  96. /**
  97. * 清除验证码
  98. */
  99. public static void clearVerifyCode() {
  100. TokenManager.getSession().removeAttribute(V_CODE);
  101. }
  102. /**
  103. * 对比验证码
  104. */
  105. public static boolean verifyCode(String code) {
  106. String v = (String) TokenManager.getVal2Session(V_CODE);
  107. return StringUtils.equals(v, StringUtils.lowerCase(code));
  108. }
  109. /**
  110. * 使用指定源生成验证码
  111. *
  112. * @param verifySize
  113. * 验证码长度
  114. * @param sources
  115. * 验证码字符源
  116. * @return
  117. */
  118. public static String generateVerifyCode(int verifySize, String sources) {
  119. if (sources == null || sources.length() == 0) {
  120. sources = VERIFY_CODES;
  121. }
  122. int codesLen = sources.length();
  123. Random rand = new Random(System.currentTimeMillis());
  124. StringBuilder verifyCode = new StringBuilder(verifySize);
  125. for (int i = 0; i < verifySize; i++) {
  126. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
  127. }
  128. return verifyCode.toString();
  129. }
  130. /**
  131. * 生成随机验证码文件,并返回验证码值
  132. *
  133. * @param w
  134. * @param h
  135. * @param outputFile
  136. * @param verifySize
  137. * @return
  138. * @throws IOException
  139. */
  140. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
  141. String verifyCode = generateVerifyCode(verifySize);
  142. outputImage(w, h, outputFile, verifyCode);
  143. return verifyCode;
  144. }
  145. /**
  146. * 输出随机验证码图片流,并返回验证码值
  147. *
  148. * @param w
  149. * @param h
  150. * @param os
  151. * @param verifySize
  152. * @return
  153. * @throws IOException
  154. */
  155. public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
  156. String verifyCode = generateVerifyCode(verifySize);
  157. outputImage(w, h, os, verifyCode);
  158. return verifyCode;
  159. }
  160. /**
  161. * 生成指定验证码图像文件
  162. *
  163. * @param w
  164. * @param h
  165. * @param outputFile
  166. * @param code
  167. * @throws IOException
  168. */
  169. public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
  170. if (outputFile == null) {
  171. return;
  172. }
  173. File dir = outputFile.getParentFile();
  174. if (!dir.exists()) {
  175. dir.mkdirs();
  176. }
  177. try {
  178. outputFile.createNewFile();
  179. FileOutputStream fos = new FileOutputStream(outputFile);
  180. outputImage(w, h, fos, code);
  181. fos.close();
  182. } catch (IOException e) {
  183. throw e;
  184. }
  185. }
  186. /**
  187. * 输出指定验证码图片流
  188. *
  189. * @param w
  190. * @param h
  191. * @param os
  192. * @param code
  193. * @throws IOException
  194. */
  195. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
  196. int verifySize = code.length();
  197. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  198. Random rand = new Random();
  199. Graphics2D g2 = image.createGraphics();
  200. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  201. Color[] colors = new Color[5];
  202. Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
  203. Color.ORANGE, Color.PINK, Color.YELLOW };
  204. float[] fractions = new float[colors.length];
  205. for (int i = 0; i < colors.length; i++) {
  206. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  207. fractions[i] = rand.nextFloat();
  208. }
  209. Arrays.sort(fractions);
  210. g2.setColor(Color.GRAY);// 设置边框色
  211. g2.fillRect(0, 0, w, h);
  212. Color c = getRandColor(200, 250);
  213. g2.setColor(c);// 设置背景色
  214. g2.fillRect(0, 2, w, h - 4);
  215. // 绘制干扰线
  216. Random random = new Random();
  217. g2.setColor(getRandColor(160, 200));// 设置线条的颜色
  218. for (int i = 0; i < 20; i++) {
  219. int x = random.nextInt(w - 1);
  220. int y = random.nextInt(h - 1);
  221. int xl = random.nextInt(6) + 1;
  222. int yl = random.nextInt(12) + 1;
  223. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  224. }
  225. // 添加噪点
  226. float yawpRate = 0.05f;// 噪声率
  227. int area = (int) (yawpRate * w * h);
  228. for (int i = 0; i < area; i++) {
  229. int x = random.nextInt(w);
  230. int y = random.nextInt(h);
  231. int rgb = getRandomIntColor();
  232. image.setRGB(x, y, rgb);
  233. }
  234. shear(g2, w, h, c);// 使图片扭曲
  235. g2.setColor(getRandColor(100, 160));
  236. int fontSize = h - 4;
  237. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  238. g2.setFont(font);
  239. char[] chars = code.toCharArray();
  240. for (int i = 0; i < verifySize; i++) {
  241. AffineTransform affine = new AffineTransform();
  242. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
  243. (w / verifySize) * i + fontSize / 2, h / 2);
  244. g2.setTransform(affine);
  245. g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
  246. }
  247. g2.dispose();
  248. ImageIO.write(image, "jpg", os);
  249. }
  250. private static Color getRandColor(int fc, int bc) {
  251. if (fc > 255)
  252. fc = 255;
  253. if (bc > 255)
  254. bc = 255;
  255. int r = fc + random.nextInt(bc - fc);
  256. int g = fc + random.nextInt(bc - fc);
  257. int b = fc + random.nextInt(bc - fc);
  258. return new Color(r, g, b);
  259. }
  260. private static int getRandomIntColor() {
  261. int[] rgb = getRandomRgb();
  262. int color = 0;
  263. for (int c : rgb) {
  264. color = color << 8;
  265. color = color | c;
  266. }
  267. return color;
  268. }
  269. private static int[] getRandomRgb() {
  270. int[] rgb = new int[3];
  271. for (int i = 0; i < 3; i++) {
  272. rgb[i] = random.nextInt(255);
  273. }
  274. return rgb;
  275. }
  276. private static void shear(Graphics g, int w1, int h1, Color color) {
  277. shearX(g, w1, h1, color);
  278. shearY(g, w1, h1, color);
  279. }
  280. private static void shearX(Graphics g, int w1, int h1, Color color) {
  281. int period = random.nextInt(2);
  282. boolean borderGap = true;
  283. int frames = 1;
  284. int phase = random.nextInt(2);
  285. for (int i = 0; i < h1; i++) {
  286. double d = (double) (period >> 1)
  287. * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
  288. g.copyArea(0, i, w1, 1, (int) d, 0);
  289. if (borderGap) {
  290. g.setColor(color);
  291. g.drawLine((int) d, i, 0, i);
  292. g.drawLine((int) d + w1, i, w1, i);
  293. }
  294. }
  295. }
  296. private static void shearY(Graphics g, int w1, int h1, Color color) {
  297. int period = random.nextInt(40) + 10; // 50;
  298. boolean borderGap = true;
  299. int frames = 20;
  300. int phase = 7;
  301. for (int i = 0; i < w1; i++) {
  302. double d = (double) (period >> 1)
  303. * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
  304. g.copyArea(i, 0, 1, h1, 0, (int) d);
  305. if (borderGap) {
  306. g.setColor(color);
  307. g.drawLine(i, (int) d, i, 0);
  308. g.drawLine(i, (int) d + h1, i, h1);
  309. }
  310. }
  311. }
  312. }