最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2020年01月09日 14:36:18   作者:陌塵吖  
這篇文章主要介紹了Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

驗證碼

防止惡意表單注冊

生成驗證碼圖片

定義寬高

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());

成果圖

ÔÚÕâÀï²åÈëͼƬÃèÊö

實現(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;
}

效果

ÔÚÕâÀï²åÈëͼƬÃèÊö

ÔÚÕâÀï²åÈëͼƬÃèÊö

項目源碼

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

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

相關(guān)文章

最新評論

炎陵县| 江安县| 宜城市| 康平县| 咸阳市| 绥芬河市| 成安县| 宝丰县| 青神县| 襄垣县| 津南区| 桦甸市| 乐业县| 冷水江市| 临朐县| 桐柏县| 云龙县| 陇西县| 新巴尔虎左旗| 多伦县| 阜平县| 平定县| 昆明市| 丹巴县| 光泽县| 南溪县| 桂林市| 会同县| 六安市| 稷山县| 大渡口区| 盘锦市| 天全县| 简阳市| 桃园市| 浪卡子县| 拉孜县| 盐城市| 张家川| 新化县| 景谷|