[Java] java验证码生成类 →→→→→进入此内容的聊天室

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

回复 "java验证码生成类"

这儿你可以回复上面这条便签

captcha