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 }