java生成圖片驗證碼

 一、生成驗證碼java

public class CodeUtil {
    private static int width = 100;// 定義圖片的width
    private static int height = 40;// 定義圖片的height
    private static int codeCount = 4;// 定義圖片上顯示驗證碼的個數
    private static int xx = 18;
    private static int fontHeight = 20;
    private static  int codeY = 27;
    private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R','T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '6', '7', '8', '9' };

    /**
     * 生成一個map集合
     * code爲生成的驗證碼
     * codePic爲生成的驗證碼BufferedImage對象
     * @return
     */
    public static Map<String,Object> generateCodeAndPic() {
        // 定義圖像buffer
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // Graphics2D gd = buffImg.createGraphics();
        // Graphics2D gd = (Graphics2D) buffImg.getGraphics();
        Graphics gd = buffImg.getGraphics();
        // 建立一個隨機數生成器類
        Random random = new Random();
        // 將圖像填充爲白色
        gd.setColor(Color.WHITE);
        gd.fillRect(0, 0, width, height);

        // 建立字體,字體的大小應該根據圖片的高度來定。
        Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
        // 設置字體。
        gd.setFont(font);

        // 畫邊框。
        gd.setColor(Color.BLACK);
        gd.drawRect(0, 0, width - 1, height - 1);

        // 隨機產生40條幹擾線,使圖象中的認證碼不易被其它程序探測到。
        gd.setColor(Color.BLACK);
        for (int i = 0; i < 30; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            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 < codeCount; i++) {
            // 獲得隨機產生的驗證碼數字。
            String code = String.valueOf(codeSequence[random.nextInt(30)]);
            // 產生隨機的顏色份量來構造顏色值,這樣輸出的每位數字的顏色值都將不一樣。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);

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

            // 將產生的四個隨機數組合在一塊兒。
            randomCode.append(code);
        }
        Map<String,Object> map  =new HashMap<String,Object>();
        //存放驗證碼
        map.put("code", randomCode);
        //存放生成的驗證碼BufferedImage對象
        map.put("codePic", buffImg);
        return map;
    }
}

二、輸出驗證碼數組

@RequestMapping("/code")
@ResponseBody
    public void doGet(HttpServletRequest req, HttpServletResponse resp){
        // 調用工具類生成的驗證碼和驗證碼圖片
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

        // 將四位數字的驗證碼保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());

        // 禁止圖像緩存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);

        resp.setContentType("image/jpeg");

        // 將圖像輸出到Servlet輸出流中。
        ServletOutputStream sos;
        try {
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

注意:輸出自己就是一張圖片 在前臺<img>標籤中的src屬性中直接寫入接口路徑便可緩存

相關文章
相關標籤/搜索