【圖片驗證碼】Java實現圖片驗證碼功能

這裏演示的是生成區分大小寫字母+數字的圖片驗證碼
生成的code可以根據自己的需求存儲
驗證碼示例


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CaptchaUtils {

    private static final Logger logger = LoggerFactory.getLogger(CaptchaUtils.class);

    public static void genCaptcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        char[] codeSequence = {'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'};
        // 定義圖像buffer
        BufferedImage buffImg = new BufferedImage(90, 28, BufferedImage.TYPE_INT_RGB);
        Graphics gd = buffImg.getGraphics();
        // 創建一個隨機數生成器類
        Random random = new Random();
        // 將圖像填充爲白色
        gd.setColor(Color.decode("#FFFFFF"));
        gd.fillRect(0, 0, 90, 28);
        // 創建字體,字體的大小應該根據圖片的高度來定。
        Font font = new Font("Serif", 1, 18);
        // 設置字體。
        gd.setFont(font);
        // 畫邊框。
        gd.setColor(Color.decode("#E0AB48"));
        gd.drawRect(0, 0, 90 - 1, 28 - 1);

        // 隨機產生40條幹擾線,使圖象中的認證碼不易被其它程序探測到。
        gd.setColor(Color.decode("#000000"));
        for (int i = 0; i < 15; i++) {
            int x = random.nextInt(90);
            int y = random.nextInt(28);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            gd.drawLine(x, y, x + xl, y + yl);
        }

        // randomCode用於保存隨機產生的驗證碼,以便用戶登錄後進行驗證。
        StringBuffer randomCode = new StringBuffer();
        int red = 0, green = 0, blue = 0;

        // 隨機產生codeCount數字的驗證碼。
        for (int i = 0; i < 4; i++) {
            // 得到隨機產生的驗證碼數字。
            String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);

            // 用隨機產生的顏色將驗證碼繪製到圖像中。
            gd.setColor(new Color(red, green, blue));
            gd.drawString(code, (i + 1) * 15, 19);

            // 將產生的四個隨機數組合在一起。
            randomCode.append(code);
        }
        // 將四位數字的驗證碼保存到Session中。
        //HttpSession session = req.getSession();
        System.out.print(randomCode);
        // session.setAttribute("code", randomCode.toString());
        logger.info("驗證碼:{}", randomCode);
        // 禁止圖像緩存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        resp.setContentType("image/jpeg");
        // 將圖像輸出到Servlet輸出流中。
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章