<%@ page contenttype="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
color getrandcolor(int fc,int bc){//給定範圍獲得隨機顏色
random random = new random();
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextint(bc-fc);
int g=fc+random.nextint(bc-fc);
int b=fc+random.nextint(bc-fc);
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 image = new bufferedimage(width, height, bufferedimage.type_int_rgb);
// 擷取圖形上下文
graphics g = image.getgraphics();
//產生隨機類
random random = new random();
// 設定背景色
g.setcolor(getrandcolor(200,250));
g.fillrect(0, 0, width, height);
//設定字型
g.setfont(new font("times new roman",font.plain,18));
//畫邊框
//g.setcolor(new color());
//g.drawrect(0,0,width-1,height-1);
// 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程式探測到
g.setcolor(getrandcolor(160,200));
for (int i=0;i<155;i++)
{
int x = random.nextint(width);
int y = random.nextint(height);
int xl = random.nextint(12);
int yl = random.nextint(12);
g.drawline(x,y,x+xl,y+yl);
}
// 取隨機產生的認證碼(4位元字)
string srand="";
for (int i=0;i<4;i++){
string rand=string.valueof(random.nextint(10));
srand+=rand;
// 將認證碼顯示到圖象中
g.setcolor(new color(20+random.nextint(110),20+random.nextint(110),20+random.nextint(110)));//調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接產生
g.drawstring(rand,13*i+6,16);
}
// 將認證碼存入session
session.setattribute("rand",srand);