圖文驗證碼的生成

備註:Alibaba Java Coding Guidelines JAVA代碼編程提示插件。java

生成圖片傳給前臺展現

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

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

/**
 * <b>function:</b> 驗證碼生成工具類
 *
 * @author hoojo
 * @project NetWorkServiceclass
 * @package com.hoo.util
 * @fileName VerifyCodeUtils.java
 * @createDate 2010-8-3 下午03:05:50
 */
public class VerifyCodeUtils {
    /*********************************************************************
     * 驗證碼寬度
     */
    public static final int WIDTH = 90;
    /***
     * 驗證碼高度
     */
    public static final int HEIGHT = 32;

    /**********************************************************************
     * 驗證碼背景顏色COLOR_FC_BG 應當小於COLOR_BC_BG
     */
    public static final int COLOR_FC_BG = 200;
    /***
     * 驗證碼背景顏色COLOR_FC_BG 應當小於COLOR_BC_BG
     */
    public static final int COLOR_BC_BG = 250;

    /**********************************************************************
     * 驗證碼背景干擾線顏色COLOR_FC_LINE 應當小於COLOR_BC_LINE
     */
    public static final int COLOR_FC_LINE = 160;
    /***
     * 驗證碼背景干擾線顏色COLOR_FC_LINE 應當小於COLOR_BC_LINE
     */
    public static final int COLOR_BC_LINE = 200;

    /***************************************************************************
     * 驗證碼顏色COLOR_FC_CODE 應當小於COLOR_BC_CODE
     */
    public static final int COLOR_FC_CODE = 20;
    /***
     * 驗證碼顏色COLOR_FC_CODE 應當小於COLOR_BC_CODE
     */
    public static final int COLOR_BC_CODE = 170;

    /***************************************************************************
     * 生成在指定範圍內的顏色
     * @param fc 範圍fc color值 小於255
     * @param bc 範圍bc color值 小於255
     * @return Color
     */
    private static Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc < 0) {
            fc = 0;
        }
        if (bc < 0) {
            bc = 1;
        }
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        if (bc == fc) {
            bc += 10;
        }
        int temp = 0;
        if (bc < fc) {
            temp = bc;
            bc = fc;
            fc = temp;
        }
        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);
    }

    /**
     * <b>function:</b> 生成圖片方法
     *
     * @param codeStrs String[]
     * @param response HttpServletResponse
     * @return boolean
     * @throws Exception
     * @createDate 2010-8-3 下午03:06:22
     * @author hoojo
     */
    public static boolean getImage(String[] codeStrs, HttpServletResponse response) throws Exception {
        response.reset();
        response.setContentType("image/jpeg");
        // 設置頁面不緩存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 在內存中建立圖象
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

        // 獲取圖形上下文
        Graphics img = image.getGraphics();
        // 生成隨機類
        Random random = new Random();

        // 設定背景色
        img.setColor(getRandColor(COLOR_FC_BG, COLOR_BC_BG));
        img.fillRect(0, 0, WIDTH, HEIGHT);

        // 設定字體
        img.setFont(new Font("Times New Roman", Font.PLAIN, 50));

        //  隨機產生155條幹擾線,使圖象中的認證碼不易被其它程序探測到
        img.setColor(getRandColor(COLOR_FC_LINE, COLOR_BC_LINE));
        for (int i = 0; i < 15; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            img.drawLine(x, y, x + xl, y + yl);
        }

        // 取隨機產生的認證碼
        for (int i = 0; i < 4; i++) {
            // 隨機字體
            img.setFont(getRandomFont());
            // 將認證碼顯示到圖象中
            img.setColor(getRandColor(COLOR_FC_CODE, COLOR_BC_CODE));
            img.drawString(codeStrs[i], 22 * i + 5, 25);
        }
        // 圖象生效
        img.dispose();
        // 輸出圖象到頁面
        return ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    /**
     * <b>function:</b> 隨機生成字體、文字大小
     *
     * @return
     * @createDate 2010-8-23 上午10:44:22
     * @author hoojo
     */
    public static Font getRandomFont() {
        String[] fonts = {"Georgia", "Verdana", "Arial", "Tahoma", "Time News Roman", "Courier New", "Arial Black", "Quantzite"};
        int fontIndex = (int) Math.round(Math.random() * (fonts.length - 1));
        int fontSize = (int) Math.round(Math.random() * 4 + 26);
        return new Font(fonts[fontIndex], Font.PLAIN, fontSize);
    }
}
複製代碼

生成四位隨機文字

public String sendVerifyCode(HttpServletResponse response) {
        String codeValue = "";
        String[] codeStrs = new String[4];
        for (int i = 0; i < 4; i++) {
            codeStrs[i] = StringUtil.getRandomChar();
            codeValue = codeValue.concat(codeStrs[i]);
        }
        try {
            VerifyCodeUtils.getImage(codeStrs, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return codeValue;
    }
複製代碼
public class StringUtil {
    /**
     * 隨機生成字符,含大寫、小寫、數字
     * <b>function:</b> 功能
     *
     * @return
     * @createDate 2010-8-23 上午10:33:55
     * @author hoojo
     */
    public static String getRandomChar() {
        int index = (int) Math.round(Math.random() * 2);
        String randChar;
        switch (index) {
            // 小寫字符
            case 0:
            case 1:
                String chars = "abcdefghkmnrstuvwxyz";
                randChar = String.valueOf(chars.charAt((int) (Math.random() * 20)));
                break;
            default: // 數字
                String charsNums = "23456789";
                randChar = String.valueOf(charsNums.charAt((int) (Math.random() * 8)));
                break;
        }
        return randChar;
    }
}
複製代碼
相關文章
相關標籤/搜索