在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

生成验证码的java类

2016-12-20 13:15| 发布者: zhangjf| 查看: 467| 评论: 0

摘要: import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.util.HashMap;import java.util.Map;import java.util.Random; //验证码public final clas ...
  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics;
  4. import java.awt.image.BufferedImage;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.util.Random;
  8. //验证码
  9. public final class ImageUtil {
  10. private static final String[] chars = { "0", "1", "2", "3", "4", "5", "6",
  11. "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
  12. "L", "M", "N", "P" };
  13. private static final int SIZE = 5;// 字符长度
  14. private static final int LINES = 7;// 干扰线
  15. private static final int WIDTH = 100;
  16. private static final int HEIGHT = 50;
  17. private static final int FONT_SIZE = 30;// 字体大小
  18. public static Map<String, BufferedImage> createImage() {
  19. StringBuffer sb = new StringBuffer();
  20. BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
  21. BufferedImage.TYPE_INT_RGB);
  22. Graphics graphic = image.getGraphics();
  23. graphic.setColor(Color.LIGHT_GRAY);
  24. graphic.fillRect(0, 0, WIDTH, HEIGHT);
  25. Random ran = new Random();
  26. // 画随机字符
  27. for (int i = 1; i <= SIZE; i++) {
  28. int r = ran.nextInt(chars.length);
  29. graphic.setColor(getRandomColor());
  30. graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
  31. graphic.drawString(chars[r], (i - 1) * WIDTH / SIZE, HEIGHT / 2);
  32. sb.append(chars[r]);// 将字符保存,存入Session
  33. }
  34. // 画干扰线
  35. for (int i = 1; i <= LINES; i++) {
  36. graphic.setColor(getRandomColor());
  37. graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
  38. ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
  39. }
  40. Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
  41. map.put(sb.toString(), image);
  42. return map;
  43. }
  44. public static Color getRandomColor() {
  45. Random ran = new Random();
  46. Color color = new Color(ran.nextInt(156), ran.nextInt(156),
  47. ran.nextInt(156));
  48. return color;
  49. }
  50. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-8-23 04:30

Copyright 2015-2025 djqfx

返回顶部