2008年6月17日 星期二

[JSP/JavaScript]圖片檢查碼

再來這個就高深了XD...
還好有同事的sample code可以拿來參考修改...
不過真的寫好到套上去可以用也是花了一天的功夫...

<%@ page contentType="image/jpeg" language="java" 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=200, height=50, fontSize=45;
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,fontSize));
//畫邊框
//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(20);
int yl = random.nextInt(20);
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,fontSize*i+random.nextInt(15),height-random.nextInt(15));
}
// 將認證碼存入SESSION
session.setAttribute("rand",sRand);
// 圖像生效
g.dispose();
// 輸出圖像到頁面
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();

裡面是把產生出來的碼存在seesion中, 所以檢核一定要submit到下一頁時才能檢查...

另外一個問題是"重新產生檢查碼"...因為jsp要被reload才會變更數字...
但是整個jsp頁面reload就很搞笑, 而且還要記頁面一堆有的沒的資料...
所以這時候就需要一個萬能的iframe~
< iframe frameborder="0" allowtransparency=true src="./ooxx.html" style="width:400px;height:85px;border:0px;cellpadding:0px;cellspacing:0px" / >

ooxx.html裡面主要就是含圖跟變更檢查碼
< img border="0" id="img_safe_code" src="./image.jsp" / >
< a href="#" class="ps style7" onclick="document.forms[0].submit();">重新產生安全碼< / a >

沒有留言: