JAVA驗證碼的實現

思路:

 

 

做驗證碼其實就是在畫圖,我們可以把它的步驟比如成如下的幾個動作:

  1. 畫出一個矩形,用做底色這個矩形大小也是驗證碼的底色.
  2. 畫出若干條幹擾線.
  3. 畫字符.比如驗證碼有四個,那麼就是要畫四個字符,這個字符當然是可以隨機的,每畫一個字符我們就用一個StringBuffer來接連保存,畫完後把這個StringBuffer對象存到session中,最後以圖片的形式顯示這個JSP頁面.

 

方法:

 

先要設置頁面的PAGE屬性:

<%@ page language="java" contentType="image/jpg;charset=gb2312" %>

我們在這裏先寫一個產生隨機顏色的方法:

Color getRandColor(int min,int max){   //隨機產生指定區域內的RGB顏色

  Random random1=new Random();

  if(min>=255)min=255;

  if(max>=255)max=255;

  int r=min+random1.nextInt(max-min);

  int g=min+random1.nextInt(max-min);

  int b=min+random1.nextInt(max-min);

  return new Color(r,g,b);

 }

//禁止頁面緩衝

  response.setHeader("Pragma","No-cache");

 response.setHeader("Cache-Control","no-cache");

 response.setDateHeader("Expires",0);

 //在緩存中創建圖形對象,然後輸出

 int width=60,height=20;  //輸出圖片的大小

 BufferedImage buff=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);  //指定緩衝的圖片和顏色結構

 Graphics g=buff.getGraphics();   //得到繪圖對象

利用graphics對象我們就可以畫圖了:

矩形:

g.setColor(getRandColor(200,250));

 g.fillRect(0,0,width,height);

干擾線:(循環的畫出細小的線條)

for(int i=1;i<=30;i++){

  int x=rand.nextInt(width);  //線條的起始位置

  int y=rand.nextInt(height);

  int tx=rand.nextInt(12);

  int ty=rand.nextInt(12);

  g.drawLine(x,y,x+tx,y+ty);

 }

驗證碼:

String coding="";  //保存得到的驗證碼字符串

 for(int i=0;i<4;i++){

  String temp=String.valueOf(rand.nextInt(10));  //0-9的數字

  coding+=temp;

  //顯示驗證碼,20-140色段

  g.setColor(getRandColor(20,140));

  g.drawString(temp,13*i+6,16);

 }

 //信息存入session

 session.setAttribute("code",coding);

清空緩存區:(這一步非常重要,不然服務器會報錯誤)

g.dispose();

 ServletOutputStream sos=response.getOutputStream();

 ImageIO.write(buff,"jpeg",sos);

 sos.flush();  //強行將緩衝區的內容輸入到頁面

 sos.close();

 sos=null;

 response.flushBuffer();

 out.clear();

 out=pageContext.pushBody();

附件中提供了原始代碼.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章