1. 程式人生 > 程式設計 >Java web實現動態圖片驗證碼的示例程式碼

Java web實現動態圖片驗證碼的示例程式碼

驗證碼

防止惡意表單註冊

生成驗證碼圖片

定義寬高

int width = 100;
int height = 50;

使用BufferedImage再記憶體中生成圖片

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

繪製背景和邊框

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

建立隨機字符集和隨機數物件

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

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

建立隨機顏色生成方法

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);
  //設定字型
  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());

成果圖

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

實現重新整理效果

新建html頁面
使用img標籤實現圖片展示

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

使用js實現重新整理效果

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

//點選連線時
var a = document.getElementById("refesh");
a.onclick = function (){
  refesh();
  //返回false防止a標籤預設href行為
  return false;
}

function refesh() {
  /**
   * 由於路徑相同時瀏覽器會自動呼叫快取中的圖片
   * 所以在連線後加時間戳解決此問題
   */
  var date = new Date().getTime();
  img.src = "identcode?" + date;
}

效果

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

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

專案原始碼

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。