標籤:
1 import java.awt.*; 2 import java.awt.image.BufferedImage; 3 import java.io.*; 4 import java.util.Random; 5 import javax.imageio.ImageIO; 6 7 public class ValidationCode { 8 9 // 圖形驗證碼的字元集合,系統將隨機從這個字串中選擇一些字元作為驗證碼10 private static String codeChars = "%#23456789abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ";11 12 // 返回一個隨機顏色(Color對象)13 private static Color getRandomColor(int minColor, int maxColor) {14 Random random = new Random();15 // 儲存minColor最大不會超過25516 if (minColor > 255)17 minColor = 255;18 // 儲存minColor最大不會超過25519 if (maxColor > 255)20 maxColor = 255;21 // 獲得紅色的隨機顏色值22 int red = minColor + random.nextInt(maxColor - minColor);23 // 獲得綠色的隨機顏色值24 int green = minColor + random.nextInt(maxColor - minColor);25 // 獲得藍色的隨機顏色值26 int blue = minColor + random.nextInt(maxColor - minColor);27 return new Color(red, green, blue);28 }29 30 protected static void getValidationCode() throws IOException {31 try {32 // 獲得驗證碼集合的長度33 int charsLength = codeChars.length();34 // 設定圖形驗證碼的長和寬(圖形的大小)35 int width = 90, height = 30;36 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);37 Graphics g = image.getGraphics();// 獲得用於輸出文字的Graphics對象38 Random random = new Random();39 g.setColor(getRandomColor(180, 250));// 隨機設定要填充的顏色40 g.fillRect(0, 0, width, height);// 填充圖形背景41 // 設定初始字型42 g.setFont(new Font("Times New Roman", Font.ITALIC, height));43 g.setColor(getRandomColor(120, 180));// 隨機設定字型顏色44 // 用於儲存最後隨機產生的驗證碼45 StringBuilder validationCode = new StringBuilder();46 // 驗證碼的隨機字型47 String[] fontNames = { "Times New Roman", "Book antiqua", "Arial" };48 // 隨機產生3個到5個驗證碼49 for (int i = 0; i < 3 + random.nextInt(3); i++) {50 // 隨機設定當前驗證碼的字元的字型51 g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC, height));52 // 隨機獲得當前驗證碼的字元53 char codeChar = codeChars.charAt(random.nextInt(charsLength));54 validationCode.append(codeChar);55 // 隨機設定當前驗證碼字元的顏色56 g.setColor(getRandomColor(10, 100));57 // 在圖形上輸出驗證碼字元,x和y都是隨機產生的58 g.drawString(String.valueOf(codeChar), 16 * i + random.nextInt(7), height - random.nextInt(6));59 }60 File file = new File("d:\\code.png"); 61 ImageIO.write(image, "png", file); 62 System.out.println(validationCode.toString());63 //byte[] data = ((DataBufferByte) image.getData().getDataBuffer()).getData();64 g.dispose();65 } catch (Exception e) {66 e.printStackTrace(); 67 }68 }69 70 public static void main(String[] args) throws IOException{71 getValidationCode();72 }73 }
Java產生驗證碼