Java生成驗證碼

jopen 8年前發布 | 40K 次閱讀 驗證碼(Captcha)

import java.awt.;
import java.awt.image.BufferedImage;
import java.io.;
import java.util.Random;
import javax.imageio.ImageIO;

public class ValidationCode {

// 圖形驗證碼的字符集合,系統將隨機從這個字符串中選擇一些字符作為驗證碼
private static String codeChars = "%#23456789abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ";

// 返回一個隨機顏色(Color對象)
private static Color getRandomColor(int minColor, int maxColor) {
    Random random = new Random();
    // 保存minColor最大不會超過255
    if (minColor > 255)
        minColor = 255;
    // 保存minColor最大不會超過255
    if (maxColor > 255)
        maxColor = 255;
    // 獲得紅色的隨機顏色值
    int red = minColor + random.nextInt(maxColor - minColor);
    // 獲得綠色的隨機顏色值
    int green = minColor + random.nextInt(maxColor - minColor);
    // 獲得藍色的隨機顏色值
    int blue = minColor + random.nextInt(maxColor - minColor);
    return new Color(red, green, blue);
}

protected static void getValidationCode() throws IOException {
    try {
        // 獲得驗證碼集合的長度
        int charsLength = codeChars.length();
        // 設置圖形驗證碼的長和寬(圖形的大小)
        int width = 90, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();// 獲得用于輸出文字的Graphics對象
        Random random = new Random();
        g.setColor(getRandomColor(180, 250));// 隨機設置要填充的顏色
        g.fillRect(0, 0, width, height);// 填充圖形背景
        // 設置初始字體
        g.setFont(new Font("Times New Roman", Font.ITALIC, height));
        g.setColor(getRandomColor(120, 180));// 隨機設置字體顏色
        // 用于保存最后隨機生成的驗證碼
        StringBuilder validationCode = new StringBuilder();
        // 驗證碼的隨機字體
        String[] fontNames = { "Times New Roman", "Book antiqua", "Arial" };
        // 隨機生成3個到5個驗證碼
        for (int i = 0; i < 3 + random.nextInt(3); i++) {
            // 隨機設置當前驗證碼的字符的字體
            g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC, height));
            // 隨機獲得當前驗證碼的字符
            char codeChar = codeChars.charAt(random.nextInt(charsLength));
            validationCode.append(codeChar);
            // 隨機設置當前驗證碼字符的顏色
            g.setColor(getRandomColor(10, 100));
            // 在圖形上輸出驗證碼字符,x和y都是隨機生成的
            g.drawString(String.valueOf(codeChar), 16 * i + random.nextInt(7), height - random.nextInt(6));
        }
        File file = new File("d:\\code.png");  
        ImageIO.write(image, "png", file);  
        System.out.println(validationCode.toString());
        //byte[] data = ((DataBufferByte) image.getData().getDataBuffer()).getData();
        g.dispose();
    } catch (Exception e) {
        e.printStackTrace();  
    }
}

public static void main(String[] args) throws IOException{
    getValidationCode();
}

}</pre>


來自: http://my.oschina.net/chenhao901007/blog/368611

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!