溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼

發(fā)布時間:2020-10-14 17:46:33 來源:腳本之家 閱讀:143 作者:陌塵吖 欄目:編程語言

驗證碼

防止惡意表單注冊

生成驗證碼圖片

定義寬高

int width = 100;
int height = 50;

使用BufferedImage再內(nèi)存中生成圖片

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

繪制背景和邊框

Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);

創(chuàng)建隨機字符集和隨機數(shù)對象

//字符集
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjijklmnopqrstuvwxyz";

//隨機數(shù)
Random ran = new Random();

創(chuàng)建隨機顏色生成方法

private Color getRandomColor(Random random) {
  //獲取隨機顏色
  int colorIndex = random.nextInt(3);
  switch (colorIndex) {
    case 0:
      return Color.BLUE;
    case 1:
      return Color.GREEN;
    case 2:
      return Color.RED;
    case 3:
      return Color.YELLOW;
    default:
      return Color.MAGENTA;
  }
}

繪制驗證碼字符

//繪制驗證碼
for (int i = 0; i < 4; i++) {
  //獲取隨機字符
  int index = ran.nextInt(str.length());
  char ch = str.charAt(index);
  //獲取隨機色
  Color randomColor = getRandomColor(ran);
  g.setColor(randomColor);
  //設(shè)置字體
  Font font = new Font("宋體", Font.BOLD, height / 2);
  g.setFont(font);
  //寫入驗證碼
  g.drawString(ch + "", (i == 0) ? width / 4 * i + 2 : width / 4 * i, height - height / 4);
}

繪制干擾線

//干擾線
for (int i = 0; i < 10; i++) {
  int x1 = ran.nextInt(width);
  int x2 = ran.nextInt(width);
  int y1 = ran.nextInt(height);
  int y2 = ran.nextInt(height);
  Color randomColor = getRandomColor(ran);
  g.setColor(randomColor);
  g.drawLine(x1, x2, y1, y2);
}

使用ImageIO輸出圖片

ImageIO.write(image, "jpg", resp.getOutputStream());

成果圖

Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼

實現(xiàn)刷新效果

新建html頁面
使用img標(biāo)簽實現(xiàn)圖片展示

<img id="identcode" src="identcode">
<a id="refesh" href="">看不清,換一張</a>

使用js實現(xiàn)刷新效果

//點擊圖片時
var img = document.getElementById("identcode");
img.onclick = function (){
  refesh();
}

//點擊連接時
var a = document.getElementById("refesh");
a.onclick = function (){
  refesh();
  //返回false防止a標(biāo)簽?zāi)J(rèn)href行為
  return false;
}

function refesh() {
  /**
   * 由于路徑相同時瀏覽器會自動調(diào)用緩存中的圖片
   * 所以在連接后加時間戳解決此問題
   */
  var date = new Date().getTime();
  img.src = "identcode?" + date;
}

效果

Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼

Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼

項目源碼

https://github.com/xiaochen0517/StudySpace/tree/master/idea/TestDemo3

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI