java生成验证码工具类,java生成图片验证码
java生成验证码工具类,java生成图片验证码,java生成彩色图片验证码,带干扰线验证码。
调用结果:
工具类调用:
@GetMapping("/validateCode")public void validateCode(HttpServletResponse response, HttpSession session) throws Exception {// 利用图片工具生成图片// 第一个参数是生成的验证码,第二个参数是生成的图片Object[] objs = ImageUtil.createImage();// 将验证码存入Sessionsession.setAttribute("imageCode", objs[0]);// 将图片输出给浏览器BufferedImage image = (BufferedImage) objs[1];response.setContentType("image/png");OutputStream os = response.getOutputStream();ImageIO.write(image, "png", os);}
工具类源代码:
public final class ImageUtil {// 验证码字符集private static final char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i','j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B','C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U','V', 'W', 'X', 'Y', 'Z'};// 字符数量private static final int SIZE = 4;// 干扰线数量private static final int LINES = 5;// 宽度private static final int WIDTH = 80;// 高度private static final int HEIGHT = 40;// 字体大小private static final int FONT_SIZE = 30;/*** 生成随机验证码及图片 Object[0]:验证码字符串; Object[1]:验证码图片。*/public static Object[] createImage() {StringBuilder sb = new StringBuilder();// 1.创建空白图片BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);// 2.获取图片画笔Graphics graphic = image.getGraphics();// 3.设置画笔颜色graphic.setColor(Color.LIGHT_GRAY);// 4.绘制矩形背景graphic.fillRect(0, 0, WIDTH, HEIGHT);// 5.画随机字符Random ran = new Random();for (int i = 0; i < SIZE; i++) {// 取随机字符索引int n = ran.nextInt(chars.length);// 设置随机颜色graphic.setColor(getRandomColor());// 设置字体大小graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));// 画字符graphic.drawString(chars[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3);// 记录字符sb.append(chars[n]);}// 6.画干扰线for (int i = 0; i < LINES; i++) {// 设置随机颜色graphic.setColor(getRandomColor());// 随机画线graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT));}// 7.返回验证码和图片return new Object[]{sb.toString(), image};}/*** 随机取色*/public static Color getRandomColor() {Random ran = new Random();return new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));}public static void main(String[] args) {createImage();}
}