1 package cn.gp.tools; 2 import java.awt.*; 3 import java.awt.image.BufferedImage; 4 import java.io.*; 5 import java.util.Random; 6 import javax.imageio.ImageIO; 7 /** 8 * int width = 70, height = 30; 9 * 验证码的w=70 h=30 用Label来接收 10 * @author 小风微灵 11 * 12 */ 13 public class ValidationCode { 14 15 16 17 /** 18 * 获取随机颜色值 19 * @param minColor 20 * @param maxColor 21 * @return 22 */ 23 private static Color getRandomColor(int minColor, int maxColor) { 24 25 Random random = new Random(); 26 // 保存minColor最大不会超过255 27 if (minColor > 255) 28 minColor = 255; 29 // 保存minColor最大不会超过255 30 if (maxColor > 255) 31 maxColor = 255; 32 // 获得红色的随机颜色值 33 int red = minColor + random.nextInt(maxColor - minColor); 34 // 获得绿色的随机颜色值 35 int green = minColor + random.nextInt(maxColor - minColor); 36 // 获得蓝色的随机颜色值 37 int blue = minColor + random.nextInt(maxColor - minColor); 38 return new Color(red, green, blue); 39 40 } 41 42 public static String getValidationCode() throws IOException { 43 44 // 用于保存最后随机生成的验证码 45 StringBuilder validationCode = new StringBuilder(); 46 47 try { 48 49 // 设置图形验证码的长和宽(图形的大小) 50 int width = 70, height = 30; 51 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 52 Graphics g = image.getGraphics();// 获得用于输出文字的Graphics对象 53 Random random = new Random(); 54 g.setColor(getRandomColor(180, 250));// 随机设置要填充的颜色 55 g.fillRect(0, 0, width, height);// 填充图形背景 56 // 设置初始字体 57 g.setFont(new Font("Times New Roman", Font.ITALIC, height)); 58 g.setColor(getRandomColor(120, 180));// 随机设置字体颜色 59 60 //干扰线 61 for(int i=0;i<155;i++){ 62 int x=random.nextInt(width); 63 int y=random.nextInt(height); 64 int x1=random.nextInt(width); 65 int y1=random.nextInt(height); 66 g.drawLine(x, y, x+x1, y+y1); 67 } 68 69 // 随机生成4个验证码 70 for (int i = 0; i < 4; i++) { 71 // 随机设置当前验证码的字符的字体 72 g.setFont(Constant.fonts[RandomUtil.getRandomInt(Constant.fonts.length-1)]); 73 // 随机获得当前验证码的字符串 74 String code=Constant.srcStrings[RandomUtil.getRandomInt(61)]; 75 validationCode.append(code); 76 // 随机设置当前验证码字符的颜色 77 g.setColor(getRandomColor(10, 100)); 78 // 在图形上输出验证码字符,x和y都是随机生成的 79 g.drawString(code, 16 * i + random.nextInt(7), height - random.nextInt(6)); 80 } 81 //名称重置 82 83 84 String path=ImageUtil.getProgramPath(); 85 86 File file = new File(path+"validates/validatecode"+(++Constant.count)+".jpg"); 87 ImageIO.write(image, "jpg", file); 88 89 90 //删除旧 的验证图片 91 File file2=new File(path+"validates/validatecode"+(Constant.count-1)+".jpg"); 92 file2.delete(); 93 94 95 g.dispose(); 96 97 } catch (Exception e){ 98 e.printStackTrace(); 99 } 100 return validationCode.toString(); 101 } 102 103 }