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