1. 程式人生 > >java手動生成驗證碼

java手動生成驗證碼

package test.response;


import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;


//手動生成驗證碼 將驗證碼輸出到瀏覽器
public class Demo_03 extends HttpServlet{


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//GUI 圖形使用者介面
//java.awt.BufferdImage
//1.建立圖片
int width=120;
int height=25;
//TYPE_INT_RGB建立一個不帶透明的bufferedimage物件
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.向圖片上畫出驗證碼和干擾線 
//獲取畫筆
Graphics pen = img.getGraphics();
//設定圖片背景色 
pen.setColor(Color.YELLOW);
//填充顏色
pen.fillRect(1, 1, width-2, height-2);
//設定邊框顏色
pen.setColor(Color.GREEN);
//畫邊
pen.drawRect(0, 0, width-1, height-1);
//設定字型顏色
pen.setColor(Color.BLUE);
pen.setFont(new Font("微軟雅黑",Font.BOLD|Font.ITALIC,15));
//生成驗證碼隨機數 將隨機數畫到圖片上 
String val = "";     
        
   Random r = new Random();     
   for(int i = 0; i < 5; i++)     
   {     
       String charOrNum = r.nextInt(2) % 2 == 0 ? "char" : "num"; // 輸出字母還是數字     
                
       if("char".equalsIgnoreCase(charOrNum)) // 字串     
       {     
           int choice = r.nextInt(2) % 2 == 0 ? 65 : 97; //取得大寫字母還是小寫字母     
           val += (char) (choice + r.nextInt(26));     
       }     
       else if("num".equalsIgnoreCase(charOrNum)) // 數字     
       {     
           val += String.valueOf(r.nextInt(10));     
       }     
   }
   pen.drawString(val, 20, 18);
//Random  r = new Random();
//int x=20;
//for(int i=0;i<4;i++){
//pen.drawString(r.nextInt(10)+"", x,20 );
//x+=20;
//}
//畫干擾線
for(int i=0;i<5;i++){
//設定干擾線顏色
pen.setColor(Color.gray);
pen.drawLine(r.nextInt(width), r.nextInt(height),r.nextInt(width), r.nextInt(height));
}

ImageIO.write(img, "jpg", resp.getOutputStream());
}


@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}

}