首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實現仿 QQ 風格圖片驗證碼生成

     編輯:Java 相關知識

項目背景與功能特點

本文分享一套使用 Java 實現的仿 QQ 風格圖片驗證碼生成工具類。該驗證碼具備以下特性:

  • 支持自定義圖片尺寸與字符長度
  • 隨機背景顏色與字符顏色
  • 字符隨機傾斜角度、平滑邊緣
  • 幹擾線、噪點、背景扭曲
  • 採用 Algerian 字體(需系統安裝),視覺效果酷似 QQ 驗證碼

註:原計劃實現字符扭曲,但因技術限制暫未完成,歡迎高手優化。

核心代碼結構

1. Servlet 入口類 AuthImage

繼承 HttpServlet,處理驗證碼圖片生成請求,將驗證碼存入 Session。

package hh.com.util;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 禁止緩存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 生成 4 位隨機驗證碼
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

        // 存入 Session
        HttpSession session = request.getSession(true);
        session.setAttribute("rand", verifyCode.toLowerCase());

        // 輸出圖片流
        int w = 200, h = 80;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }
}

2. 工具類 VerifyCodeUtils 核心實現

包含驗證碼字符源定義、隨機生成、圖片繪製(幹擾線、噪點、扭曲、字符繪製)等完整邏輯。

package hh.com.util;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import javax.imageio.ImageIO;

public class VerifyCodeUtils {
    // 字符源(去除易混淆字符 1,0,i,o)
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();

    // 生成驗證碼字符串
    public static String generateVerifyCode(int verifySize) { ... }
    public static String generateVerifyCode(int verifySize, String sources) { ... }

    // 輸出圖片到文件/流
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException { ... }
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException { ... }
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException { ... }

    // 核心圖片繪製邏輯
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 隨機漸變背景
        Color[] colors = new Color[5];
        Color[] colorSpaces = { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[random.nextInt(colorSpaces.length)];
            fractions[i] = random.nextFloat();
        }
        Arrays.sort(fractions);

        // 邊框與背景
        g2.setColor(Color.GRAY);
        g2.fillRect(0, 0, w, h);
        Color c = getRandColor(200, 250);
        g2.setColor(c);
        g2.fillRect(0, 2, w, h - 4);

        // 繪製幹擾線
        g2.setColor(getRandColor(160, 200));
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1), y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1, yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪點
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w), y = random.nextInt(h);
            image.setRGB(x, y, getRandomIntColor());
        }

        // 背景扭曲
        shear(g2, w, h, c);

        // 繪製驗證碼字符(隨機旋傾斜)
        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * random.nextDouble() * (random.nextBoolean() ? 1 : -1),
                    (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    // 輔助方法:隨機顏色、扭曲算法、主方法測試等
    private static Color getRandColor(int fc, int bc) { ... }
    private static int getRandomIntColor() { ... }
    private static int[] getRandomRgb() { ... }
    private static void shear(Graphics g, int w1, int h1, Color color) { ... }
    private static void shearX(Graphics g, int w1, int h1, Color color) { ... }
    private static void shearY(Graphics g, int w1, int h1, Color color) { ... }

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

3. web.xml Servlet 映射配置

<servlet>
    <servlet-name>AuthImage</servlet-name>
    <servlet-class>hh.com.util.AuthImage</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>AuthImage</servlet-name>
    <url-pattern>/authImage</url-pattern>
</servlet-mapping>

使用說明

  1. 確保系統安裝 Algerian 字體(無則從網上下載放入系統 Fonts 目錄)。
  2. 將 AuthImage 和 VerifyCodeUtils 放入項目對應包路徑。
  3. 在 web.xml 中配置 Servlet 映射。
  4. 前端頁面通過 <img src="/authImage" /> 請求驗證碼圖片。
  5. 用戶提交表單時,後台從 Session 獲取 rand 屬性與用戶輸入比對(忽略大小寫)。

效果展示

生成的驗證碼圖片具有隨機背景、傾斜字符、幹擾線及噪點,視覺風格酷似 QQ 登錄驗證碼,有效防止機器識別。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved