圖片驗證

網(wǎng)頁登錄中圖片驗證的實現(xiàn),核心代碼如下所示:
創(chuàng)建圖片資源 BufferedImage image = new BufferedImage(WIDTH, Hight, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();
* 設(shè)置內(nèi)容
/
private void setContent(Graphics2D g) {
g.setColor(Color.BLACK);
g.setFont(new Font("宋體", Font.BOLD,40));
int x = 20;
int y = 40;
for(int i = 0; i < 4; i ++){
double degree = new Random().nextInt()%30 ;
g.rotate(degree * Math.PI/180, x + 20, y - 20);
String num = new Random().nextInt(9) + "";
g.drawString(num, x, y);
g.rotate(-degree
Math.PI/180, x + 20, y - 20);
x += 30;
}

}
/**
 * 設(shè)置干擾線
 * @param g
 */
private void setLine(Graphics g) {
    g.setColor(Color.BLACK);
    for(int i = 0; i < 5; i ++){
        int x1 = new Random().nextInt(WIDTH);
        int y1 = new Random().nextInt(Hight);
        
        int x2 = new Random().nextInt(WIDTH);
        int y2 = new Random().nextInt(Hight);
        g.drawLine(x1, y1, x2, y2);
    }
}

/**
 * 畫出邊框
 * @param g
 */
private void setFrame(Graphics g) {
    g.setColor(Color.BLACK);
    g.drawRect(0, 0, WIDTH, Hight);
}

/**
 * 填充背景顏色
 * @param g
 */
private void setBackgroundColor(Graphics g) {
    g.setColor(Color.WHITE);
    g.fillRect(1, 1, WIDTH-2, Hight-2);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
}

//將數(shù)據(jù)寫入流中
ImageIO.write(image, "jpg", response.getOutputStream());
在登錄中我們有時會使用漢字認證,漢字的范圍:\u4e00-\u9fa5。
實現(xiàn)點擊圖片換一張,在js點擊事件中的代碼:
this.src = this.src + "?" + new Date().getTime();
this:指的是圖片image標(biāo)簽
src:指的是servlet資源,將資源重新賦值給image,就是再次向服務(wù)器發(fā)送請求.
"?" + new Date().getTime():由于緩存的存在,這句話是為了避免和上次發(fā)送的請求相同而取本地緩存。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容