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

用 Java 圖形 API 產生驗證碼圖片

驗證碼的用意不是「加密」,而是「增加自動化腳本的辨識成本」。做法是在圖片上畫出隨機字元,再鋪上大量干擾線與隨機色彩,讓單純的 OCR 難以還原。以下用 BufferedImage 搭配 Graphics 實作一個可直接輸出到 OutputStream 的版本。

package cn.net.seek.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

public class ImgZoom {

    // 驗證碼圖片中可出現的字元集,可依需要增減
    private char mapTable[] = {
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
        'O','P','Q','R','S','T','U','V','W','X','Y','Z',
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
        'o','p','q','r','s','t','u','v','w','x','y','z',
        '0','1','2','3','4','5','6','7','8','9'
    };

    /**
     * 產生驗證碼
     * @param width  寬度,例如 60
     * @param height 高度,例如 24
     * @param os     輸出流
     * @return 產生的隨機字串
     */
    public String getCertPic(int width, int height, OutputStream os) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();

        // 背景填白
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, width, height);

        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

        // 畫 155 條干擾線,降低被程式探測的機率
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        // 取 5 位隨機字元並逐一畫到圖上
        String sRand = "";
        for (int i = 0; i < 5; i++) {
            String rand = mapTable[(int) (mapTable.length * Math.random())] + "";
            sRand += rand;
            // 直接生成 RGB,避免種子過於接近導致顏色重複
            g.setColor(new Color(20 + random.nextInt(110),
                                 20 + random.nextInt(110),
                                 20 + random.nextInt(110)));
            g.drawString(rand, 10 * i + 3, (int) (Math.random() * 9 + 14));
        }

        g.dispose();   // 釋放圖形上下文

        try {
            ImageIO.write(image, "JPEG", os);   // 輸出圖像到頁面
        } catch (IOException e) {
            return "";
        }
        return sRand;
    }

    // 在給定範圍內取得隨機顏色
    Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}

幾個實作細節

干擾線的顏色刻意壓在 160–200 的區間,比字元顏色淡,干擾之餘又不至於蓋掉主體。字元本身則用 20–130 的隨機 RGB,讓每個字顏色都不同。若改用 getRandColor 之類的方法反覆取色,常會因為 Random 種子過於接近而拿到相同顏色,這裡索性直接內聯生成。

最後 g.dispose() 不可省略,圖形上下文持有原生資源,不釋放會累積。而在 Web 環境使用時,記得回傳的 sRand 要存進 session 作為比對依據,並且不要把答案寫進任何可被用戶端讀取的地方——驗證碼的安全性建立在「答案只在伺服器端」這個前提上。

Copyright © Linux教程網 All Rights Reserved