VerifyCodeUtil

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

关键方法

  1. outputImage()
  2. generateVerifyCode(int verifySize, String sources)

关键点

  • 使用awt生成图片字节
  • IO流传输

不熟悉的Jar

  • javax.imageio.ImageIO 图片IO
  • java.security.SecureRandom JAVA 1.8 SecureRandom