Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Java 打造驗證碼圖像生成器

本文用 Java 實作一個簡易的驗證碼產生器:輸出一張由 4 位數字與字母隨機組成的圖像。為了避免被光學字元識別(OCR,Optical Character Recognition)之類的程式直接讀出圖中的字元而失去防護效果,我們還會在圖上畫幾條干擾線,並讓每個字元帶一點隨機旋轉與位移。

package password;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * 使用 Java 設計驗證碼生成程序
 */
public class Verification {

    // 圖像長度
    private int width = 100;
    // 圖像寬度
    private int height = 40;
    // 驗證碼的長度
    private int number = 4;
    // 驗證碼隨機生成的字符集(已排除易混淆的 0/O、1/l/I 等)
    private String password = "abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXYZ23456789";

    /**
     * 獲取驗證碼圖像
     *
     * @return 驗證碼圖像
     */
    public BufferedImage getImage() {
        /* BufferedImage 描述具有可訪問圖像數據緩衝區的 Image,
         * 建構子可指定預定義的圖像類型 */
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 獲取畫筆
        Graphics g = image.getGraphics();

        // 設置背景色並填充背景矩形
        g.setColor(getRandomColor(200, 255));
        g.fillRect(0, 0, width, height);

        // 畫邊框
        g.setColor(Color.blue);
        g.drawRect(0, 0, width - 1, height - 1);

        /* 生成隨機驗證碼 */
        int len = password.length();
        // 設置驗證碼字體
        g.setFont(new Font("楷體", Font.HANGING_BASELINE, 20));

        // 循環生成驗證碼各字符
        Random random = new Random();
        for (int i = 0; i < number; i++) {
            // 隨機取一個字符
            String randStr = String.valueOf(password.charAt(random.nextInt(len)));
            // 單個字符繪制寬度
            int w = this.width / this.number;
            // 當前字符繪制原點
            int x = w * i;
            int y = this.height / 2 + random.nextInt(this.height / 3);
            // 將該字符畫到圖像中
            drawString(g, x, y, randStr);
        }

        // 畫干擾線
        drawLine(g, 10);

        // 釋放畫筆
        g.dispose();
        return image;
    }

    /**
     * 畫驗證碼字符串單個字符
     *
     * @param g      圖像上下文
     * @param width  字符所占寬度
     * @param height 字符所占高度
     * @param randStr 待繪制字符串
     */
    private void drawString(Graphics g, int width, int height, String randStr) {
        Random rand = new Random();
        // 隨機生成字符旋轉角度(-30 到 30 度)
        int degree = rand.nextInt(60);
        if (degree > 30) {
            degree = 30 - degree;
        }
        // 設置字體顏色
        g.setColor(getRandomColor(0, 50));
        // 轉換為 Graphics2D
        Graphics2D g2 = (Graphics2D) g.create();
        // 平移原點,translate 會把上下文原點移到當前坐標系中的 (x, y)
        g2.translate(width + rand.nextInt(5), height + rand.nextInt(5));
        // 旋轉文本(單位為弧度)
        g2.rotate(degree * Math.PI / 180);
        // 畫文本,注意此處坐標是相對平移後原點的位置
        g2.drawString(randStr, 0, 0);
    }

    /**
     * 畫隨機干擾線
     *
     * @param g     圖形上下文(畫筆)
     * @param count 干擾線條數
     */
    private void drawLine(Graphics g, int count) {
        Random random = new Random();
        // 循環繪制每條干擾線
        for (int j = 0; j < count; j++) {
            // 設置線條隨機顏色
            g.setColor(getRandomColor(180, 200));
            // 生成隨機起點與終點坐標
            int x1 = random.nextInt(this.width);
            int y1 = random.nextInt(this.height);
            int x2 = random.nextInt(this.width);
            int y2 = random.nextInt(this.height);
            // 畫線條
            g.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 獲取隨機顏色
     *
     * @param i 顏色下限值
     * @param j 顏色上限值
     * @return 隨機顏色對象
     */
    private Color getRandomColor(int i, int j) {
        if (i > j) {
            int tmp = i;
            i = j;
            j = tmp;
        }
        if (j > 225) {
            j = 225;
        }
        if (i < 0) {
            i = 0;
        }
        // values in the range (0 - 255): red green blue
        int r = i + (int) (Math.random() * (j - i));
        int g = i + (int) (Math.random() * (j - i));
        int b = i + (int) (Math.random() * (j - i));
        return new Color(r, g, b);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("驗證碼");
        frame.setSize(200, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        Verification cation = new Verification();

        JLabel lbl = new JLabel(new ImageIcon(cation.getImage()));
        frame.add(lbl);
        frame.setVisible(true);
    }
}

關鍵在幾個細節:背景與字元用不同區間的隨機色,讓對比度不會太高;每個字元透過 Graphics2D 的 translate 與 rotate 做隨機位移與旋轉;最後再鋪上隨機干擾線。這幾層疊加起來,就足以讓單純的 OCR 難以穩定辨識。

Copyright © Linux教程網 All Rights Reserved