VerifyCodeUtil
1 package jf.utils; 2 3 4 import java.awt.Color; 5 import java.awt.Font; 6 import java.awt.Graphics; 7 import java.awt.Graphics2D; 8 import java.awt.RenderingHints; 9 import java.awt.geom.AffineTransform; 10 import java.awt.image.BufferedImage; 11 import java.io.File; 12 import java.io.FileOutputStream; 13 import java.io.IOException; 14 import java.io.OutputStream; 15 import java.util.Arrays; 16 import java.util.Random; 17 18 19 import javax.imageio.ImageIO; 20 21 22 /** 23 * 生成验证码图片的工具类 24 * 25 */ 26 public class VerifyCodeUtils { 27 28 29 // 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符 30 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; 31 private static Random random = new Random(); 32 33 34 /** 35 * 使用系统默认字符源生成验证码 36 * 37 * @param verifySize 验证码长度 38 * @return 39 */ 40 public static String generateVerifyCode(int verifySize) { 41 return generateVerifyCode(verifySize, VERIFY_CODES); 42 } 43 44 45 /** 46 * 使用指定源生成验证码 47 * 48 * @param verifySize 验证码长度 49 * @param sources 验证码字符源 50 * @return 51 */ 52 public static String generateVerifyCode(int verifySize, String sources) { 53 if (sources == null || sources.length() == 0) { 54 sources = VERIFY_CODES; 55 } 56 int codesLen = sources.length(); 57 Random rand = new Random(System.currentTimeMillis()); 58 StringBuilder verifyCode = new StringBuilder(verifySize); 59 for (int i = 0; i < verifySize; i++) { 60 verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1))); 61 } 62 return verifyCode.toString(); 63 } 64 65 66 /** 67 * 生成随机验证码文件,并返回验证码值 68 * 69 * @param w 70 * @param h 71 * @param outputFile 72 * @param verifySize 73 * @return 74 * @throws IOException 75 */ 76 public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException { 77 String verifyCode = generateVerifyCode(verifySize); 78 outputImage(w, h, outputFile, verifyCode); 79 return verifyCode; 80 } 81 82 83 /** 84 * 输出随机验证码图片流,并返回验证码值 85 * 86 * @param w 87 * @param h 88 * @param os 89 * @param verifySize 90 * @return 91 * @throws IOException 92 */ 93 public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException { 94 String verifyCode = generateVerifyCode(verifySize); 95 outputImage(w, h, os, verifyCode); 96 return verifyCode; 97 } 98 99 100 /** 101 * 生成指定验证码图像文件 102 * 103 * @param w 104 * @param h 105 * @param outputFile 106 * @param code 107 * @throws IOException 108 */ 109 public static void outputImage(int w, int h, File outputFile, String code) throws IOException { 110 if (outputFile == null) { 111 return; 112 } 113 File dir = outputFile.getParentFile(); 114 if (!dir.exists()) { 115 dir.mkdirs(); 116 } 117 try { 118 outputFile.createNewFile(); 119 FileOutputStream fos = new FileOutputStream(outputFile); 120 outputImage(w, h, fos, code); 121 fos.close(); 122 } catch (IOException e) { 123 throw e; 124 } 125 } 126 127 128 /** 129 * 输出指定验证码图片流 130 * 131 * @param w 132 * @param h 133 * @param os 134 * @param code 135 * @throws IOException 136 */ 137 public static void outputImage(int w, int h, OutputStream os, String code) throws IOException { 138 int verifySize = code.length(); 139 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 140 Random rand = new Random(); 141 Graphics2D g2 = image.createGraphics(); 142 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 143 Color[] colors = new Color[5]; 144 Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, 145 Color.ORANGE, Color.PINK, Color.YELLOW }; 146 float[] fractions = new float[colors.length]; 147 for (int i = 0; i < colors.length; i++) { 148 colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; 149 fractions[i] = rand.nextFloat(); 150 } 151 Arrays.sort(fractions); 152 153 g2.setColor(Color.GRAY);// 设置边框色 154 g2.fillRect(0, 0, w, h); 155 156 Color c = getRandColor(200, 250); 157 g2.setColor(c);// 设置背景色 158 g2.fillRect(0, 2, w, h - 4); 159 160 // 绘制干扰线 161 Random random = new Random(); 162 g2.setColor(getRandColor(160, 200));// 设置线条的颜色 163 for (int i = 0; i < 20; i++) { 164 int x = random.nextInt(w - 1); 165 int y = random.nextInt(h - 1); 166 int xl = random.nextInt(6) + 1; 167 int yl = random.nextInt(12) + 1; 168 g2.drawLine(x, y, x + xl + 40, y + yl + 20); 169 } 170 171 // 添加噪点 172 float yawpRate = 0.05f;// 噪声率 173 int area = (int) (yawpRate * w * h); 174 for (int i = 0; i < area; i++) { 175 int x = random.nextInt(w); 176 int y = random.nextInt(h); 177 int rgb = getRandomIntColor(); 178 image.setRGB(x, y, rgb); 179 } 180 181 shear(g2, w, h, c);// 使图片扭曲 182 183 g2.setColor(getRandColor(100, 160)); 184 int fontSize = h - 4; 185 Font font = new Font("Algerian", Font.ITALIC, fontSize); 186 g2.setFont(font); 187 char[] chars = code.toCharArray(); 188 for (int i = 0; i < verifySize; i++) { 189 AffineTransform affine = new AffineTransform(); 190 affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), 191 (w / verifySize) * i + fontSize / 2, h / 2); 192 g2.setTransform(affine); 193 g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10); 194 } 195 196 g2.dispose(); 197 ImageIO.write(image, "jpg", os); 198 } 199 200 201 private static Color getRandColor(int fc, int bc) { 202 if (fc > 255) 203 fc = 255; 204 if (bc > 255) 205 bc = 255; 206 int r = fc + random.nextInt(bc - fc); 207 int g = fc + random.nextInt(bc - fc); 208 int b = fc + random.nextInt(bc - fc); 209 return new Color(r, g, b); 210 } 211 212 213 private static int getRandomIntColor() { 214 int[] rgb = getRandomRgb(); 215 int color = 0; 216 for (int c : rgb) { 217 color = color << 8; 218 color = color | c; 219 } 220 return color; 221 } 222 223 224 private static int[] getRandomRgb() { 225 int[] rgb = new int[3]; 226 for (int i = 0; i < 3; i++) { 227 rgb[i] = random.nextInt(255); 228 } 229 return rgb; 230 } 231 232 233 private static void shear(Graphics g, int w1, int h1, Color color) { 234 shearX(g, w1, h1, color); 235 shearY(g, w1, h1, color); 236 } 237 238 239 private static void shearX(Graphics g, int w1, int h1, Color color) { 240 int period = random.nextInt(2); 241 242 boolean borderGap = true; 243 int frames = 1; 244 int phase = random.nextInt(2); 245 246 for (int i = 0; i < h1; i++) { 247 double d = (double) (period >> 1) 248 * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); 249 g.copyArea(0, i, w1, 1, (int) d, 0); 250 if (borderGap) { 251 g.setColor(color); 252 g.drawLine((int) d, i, 0, i); 253 g.drawLine((int) d + w1, i, w1, i); 254 } 255 } 256 } 257 258 259 private static void shearY(Graphics g, int w1, int h1, Color color) { 260 int period = random.nextInt(40) + 10; // 50; 261 262 boolean borderGap = true; 263 int frames = 20; 264 int phase = 7; 265 for (int i = 0; i < w1; i++) { 266 double d = (double) (period >> 1) 267 * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); 268 g.copyArea(i, 0, 1, h1, 0, (int) d); 269 if (borderGap) { 270 g.setColor(color); 271 g.drawLine(i, (int) d, i, 0); 272 g.drawLine(i, (int) d + h1, i, h1); 273 } 274 } 275 } 276 277 278 //生成一张验证码图片,并保存到项目的verifyCodeImg文件夹下 279 @SuppressWarnings("finally") 280 public static String createOneCodeImage(){ 281 String imgName = ""; 282 try { 283 File dir = new File("./verifyCodeImg"); 284 int w = 95, h = 50; 285 String verifyCode = generateVerifyCode(4); 286 File file = new File(dir, verifyCode + ".jpg"); 287 outputImage(w, h, file, verifyCode); 288 imgName = verifyCode; 289 } catch (IOException e) { 290 imgName = ""; 291 e.printStackTrace(); 292 }finally{ 293 return imgName; 294 } 295 } 296 297 298 public static void main(String[] args) throws IOException { 299 String codeImage = VerifyCodeUtils.createOneCodeImage(); 300 System.out.println(codeImage); 301 } 302 303 }