Java简单生成登录图片验证码

我就是我 2023-01-12 14:56 275阅读 0赞

Java简单生成登录图片验证码


用一个类就可以生成验证码,拿去piao!!


页面显示代码:

  1. <body>
  2. <form action="">
  3. 验证码:<input type="text" name="code">
  4. <!--src会自动请求访问服务器 获得 验证码资源-->
  5. <img src="/imgCode" id="img" alt="验证码" onclick="changeImg()">
  6. </form>
  7. </body>
  8. <script> /*点击图片事件,修改图片路径 随机获得验证码*/ function changeImg() { /*修改图片访问路径 不能一样不然浏览器缓冲机制 发现src没有变化就不去访问服务器*/ document.getElementById("img").src='/imgCode?'+new Date().getTime() } </script>

后台代码:

  1. @WebServlet("/imgCode")
  2. public class LoginSourceServlet extends HttpServlet {
  3. private UserService userService=new UserServiceImpl();
  4. @Override/*生成code验证码*/
  5. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  6. //outputVerifyImage此方法可以获得一个图片验证码,并返回验证码中的验证数值,可以用前台传过来的验证码与之进行比对
  7. //宽度 高度 输出流 几个位数的验证码
  8. String code = GenerateCode.outputVerifyImage(100, 40, resp.getOutputStream(), 4);
  9. req.getSession().setAttribute("code",code);
  10. }

这里我只用了:GenerateCode 类,可以把它当做一个工具类来使用

显示效果:
在这里插入图片描述

工具类代码:(直接粘贴复制即可)

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

发表评论

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

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

相关阅读

    相关 登录图片验证

    页面刷新时,自动发送获取验证码到服务端 输入验证码登录,登录成功返回token 通过token获取用户详情,跳转主页 //获取验证码图片 @GetMappi

    相关 Java生成图片验证

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