package com.linln.common.utils;@b@@b@import java.awt.*;@b@import java.awt.image.BufferedImage;@b@import java.util.Random;@b@@b@/**@b@ * 验证码生成工具@b@ * @author 小懒虫@b@ * @date 2018/11/7@b@ */@b@public class CaptchaUtil {@b@@b@ private final static int WIDTH = 120;@b@ private final static int HEIGHT = 45;@b@ private final static int LENGTH = 4;@b@ private final static String EX_CHARS = "10ioIO";@b@@b@ /**@b@ * 生成随机验证码@b@ */@b@ public static String getRandomCode(){@b@ StringBuilder sb = new StringBuilder();@b@ Random random = new Random();@b@ int i = 0;@b@ while(i< LENGTH){@b@ int t=random.nextInt(123);@b@ if((t>=97||(t>=65&&t<=90)||(t>=48&&t<=57))&&(EX_CHARS ==null|| EX_CHARS.indexOf((char)t)<0)){@b@ sb.append((char)t);@b@ i++;@b@ }@b@ }@b@ return sb.toString();@b@ }@b@@b@ /**@b@ * 生成验证码图片@b@ * @param randomCode 验证码@b@ */@b@ public static BufferedImage genCaptcha(String randomCode){@b@ // 创建画布@b@ BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);@b@ Graphics2D g = image.createGraphics();@b@ g.setColor(getRandColor(200, 250));@b@ g.fillRect(0, 0, WIDTH, HEIGHT);@b@ Random random = new Random();@b@@b@ // 绘制干扰线@b@ g.setColor(getRandColor(100, 180));@b@ for (int i = 0; i < 30; i++) {@b@ int x = random.nextInt(WIDTH - 1);@b@ int y = random.nextInt(HEIGHT - 1);@b@ int xl = random.nextInt(WIDTH / 2);@b@ int yl = random.nextInt(WIDTH / 2);@b@ g.drawLine(x, y, x + xl, y + yl + 20);@b@ }@b@@b@ // 添加噪点@b@ float rate = 0.1f;@b@ int area = (int) (rate * WIDTH * HEIGHT);@b@ for (int i = 0; i < area; i++) {@b@ int x = random.nextInt(WIDTH);@b@ int y = random.nextInt(HEIGHT);@b@ image.setRGB(x, y, getRandColor(100, 200).getRGB());@b@ }@b@@b@ // 绘制验证码@b@ int size = HEIGHT -4;@b@ Font font = new Font("Algerian", Font.ITALIC, size);@b@ g.setFont(font);@b@ char[] chars = randomCode.toCharArray();@b@ for(int i = 0; i < randomCode.length(); i++){@b@ g.drawChars(chars, i, 1, ((WIDTH -10) / randomCode.length()) * i + 5, HEIGHT /2 + size/2 - 6);@b@ }@b@@b@ g.dispose();@b@ return image;@b@ }@b@@b@ /**@b@ * 获取相应范围的随机颜色@b@ * @param min 最小值@b@ * @param max 最大值@b@ */@b@ private static Color getRandColor(int min, int max) {@b@ min = min > 255 ? 255 : min;@b@ max = max > 255 ? 255 : max;@b@ Random random = new Random();@b@ int r = min + random.nextInt(max - min);@b@ int g = min + random.nextInt(max - min);@b@ int b = min + random.nextInt(max - min);@b@ return new Color(r, g, b);@b@ }@b@@b@}