生成验证码图片的完整Java工具代码

清疚 2023-10-11 22:23 92阅读 0赞
  1. package 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 CheckCodeUtil {
  16. public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  17. private static Random random = new Random();
  18. /**
  19. * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
  20. * w:宽 h:高 verifySize;随机数数量
  21. * @param w
  22. * @param h
  23. * @param os
  24. * @param verifySize
  25. * @return
  26. * @throws IOException
  27. */
  28. public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
  29. String verifyCode = generateVerifyCode(verifySize);
  30. outputImage(w, h, os, verifyCode);
  31. return verifyCode;
  32. }
  33. /**
  34. * 使用系统默认字符源生成验证码
  35. *
  36. * @param verifySize 验证码长度
  37. * @return
  38. */
  39. public static String generateVerifyCode(int verifySize) {
  40. return generateVerifyCode(verifySize, VERIFY_CODES);
  41. }
  42. /**
  43. * 使用指定源生成验证码
  44. *
  45. * @param verifySize 验证码长度
  46. * @param sources 验证码字符源
  47. * @return
  48. */
  49. public static String generateVerifyCode(int verifySize, String sources) {
  50. // 未设定展示源的字码,赋默认值大写字母+数字
  51. if (sources == null || sources.length() == 0) {
  52. sources = VERIFY_CODES;
  53. }
  54. int codesLen = sources.length();
  55. Random rand = new Random(System.currentTimeMillis());
  56. StringBuilder verifyCode = new StringBuilder(verifySize);
  57. for (int i = 0; i < verifySize; i++) {
  58. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
  59. }
  60. return verifyCode.toString();
  61. }
  62. /**
  63. * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
  64. *
  65. * @param w
  66. * @param h
  67. * @param outputFile
  68. * @param verifySize
  69. * @return
  70. * @throws IOException
  71. */
  72. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
  73. String verifyCode = generateVerifyCode(verifySize);
  74. outputImage(w, h, outputFile, verifyCode);
  75. return verifyCode;
  76. }
  77. /**
  78. * 生成指定验证码图像文件
  79. *
  80. * @param w
  81. * @param h
  82. * @param outputFile
  83. * @param code
  84. * @throws IOException
  85. */
  86. public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
  87. if (outputFile == null) {
  88. return;
  89. }
  90. File dir = outputFile.getParentFile();
  91. //文件不存在
  92. if (!dir.exists()) {
  93. //创建
  94. dir.mkdirs();
  95. }
  96. try {
  97. outputFile.createNewFile();
  98. FileOutputStream fos = new FileOutputStream(outputFile);
  99. outputImage(w, h, fos, code);
  100. fos.close();
  101. } catch (IOException e) {
  102. throw e;
  103. }
  104. }
  105. /**
  106. * 输出指定验证码图片流
  107. *
  108. * @param w
  109. * @param h
  110. * @param os
  111. * @param code
  112. * @throws IOException
  113. */
  114. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
  115. int verifySize = code.length();
  116. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  117. Random rand = new Random();
  118. Graphics2D g2 = image.createGraphics();
  119. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  120. // 创建颜色集合,使用java.awt包下的类
  121. Color[] colors = new Color[5];
  122. Color[] colorSpaces = new Color[]{
  123. Color.WHITE, Color.CYAN,
  124. Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
  125. Color.PINK, Color.YELLOW};
  126. float[] fractions = new float[colors.length];
  127. for (int i = 0; i < colors.length; i++) {
  128. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  129. fractions[i] = rand.nextFloat();
  130. }
  131. Arrays.sort(fractions);
  132. // 设置边框色
  133. g2.setColor(Color.GRAY);
  134. g2.fillRect(0, 0, w, h);
  135. Color c = getRandColor(200, 250);
  136. // 设置背景色
  137. g2.setColor(c);
  138. g2.fillRect(0, 2, w, h - 4);
  139. // 绘制干扰线
  140. Random random = new Random();
  141. // 设置线条的颜色
  142. g2.setColor(getRandColor(160, 200));
  143. for (int i = 0; i < 20; i++) {
  144. int x = random.nextInt(w - 1);
  145. int y = random.nextInt(h - 1);
  146. int xl = random.nextInt(6) + 1;
  147. int yl = random.nextInt(12) + 1;
  148. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  149. }
  150. // 添加噪点
  151. // 噪声率
  152. float yawpRate = 0.05f;
  153. int area = (int) (yawpRate * w * h);
  154. for (int i = 0; i < area; i++) {
  155. int x = random.nextInt(w);
  156. int y = random.nextInt(h);
  157. // 获取随机颜色
  158. int rgb = getRandomIntColor();
  159. image.setRGB(x, y, rgb);
  160. }
  161. // 添加图片扭曲
  162. shear(g2, w, h, c);
  163. g2.setColor(getRandColor(100, 160));
  164. int fontSize = h - 4;
  165. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  166. g2.setFont(font);
  167. char[] chars = code.toCharArray();
  168. for (int i = 0; i < verifySize; i++) {
  169. AffineTransform affine = new AffineTransform();
  170. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
  171. g2.setTransform(affine);
  172. g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
  173. }
  174. g2.dispose();
  175. ImageIO.write(image, "jpg", os);
  176. }
  177. /**
  178. * 随机颜色
  179. *
  180. * @param fc
  181. * @param bc
  182. * @return
  183. */
  184. private static Color getRandColor(int fc, int bc) {
  185. if (fc > 255) {
  186. fc = 255;
  187. }
  188. if (bc > 255) {
  189. bc = 255;
  190. }
  191. int r = fc + random.nextInt(bc - fc);
  192. int g = fc + random.nextInt(bc - fc);
  193. int b = fc + random.nextInt(bc - fc);
  194. return new Color(r, g, b);
  195. }
  196. private static int getRandomIntColor() {
  197. int[] rgb = getRandomRgb();
  198. int color = 0;
  199. for (int c : rgb) {
  200. color = color << 8;
  201. color = color | c;
  202. }
  203. return color;
  204. }
  205. private static int[] getRandomRgb() {
  206. int[] rgb = new int[3];
  207. for (int i = 0; i < 3; i++) {
  208. rgb[i] = random.nextInt(255);
  209. }
  210. return rgb;
  211. }
  212. private static void shear(Graphics g, int w1, int h1, Color color) {
  213. shearX(g, w1, h1, color);
  214. shearY(g, w1, h1, color);
  215. }
  216. private static void shearX(Graphics g, int w1, int h1, Color color) {
  217. int period = random.nextInt(2);
  218. boolean borderGap = true;
  219. int frames = 1;
  220. int phase = random.nextInt(2);
  221. for (int i = 0; i < h1; 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(0, i, w1, 1, (int) d, 0);
  227. if (borderGap) {
  228. g.setColor(color);
  229. g.drawLine((int) d, i, 0, i);
  230. g.drawLine((int) d + w1, i, w1, i);
  231. }
  232. }
  233. }
  234. private static void shearY(Graphics g, int w1, int h1, Color color) {
  235. int period = random.nextInt(40) + 10; // 50;
  236. boolean borderGap = true;
  237. int frames = 20;
  238. int phase = 7;
  239. for (int i = 0; i < w1; i++) {
  240. double d = (double) (period >> 1)
  241. * Math.sin((double) i / (double) period
  242. + (6.2831853071795862D * (double) phase)
  243. / (double) frames);
  244. g.copyArea(i, 0, 1, h1, 0, (int) d);
  245. if (borderGap) {
  246. g.setColor(color);
  247. g.drawLine(i, (int) d, i, 0);
  248. g.drawLine(i, (int) d + h1, i, h1);
  249. }
  250. }
  251. }
  252. }

发表评论

表情:
评论列表 (有 0 条评论,92人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java生成图片验证

    功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。 VerifyCodeUtils类,生成图片流,然后不同框