<%@ page contentType="image/jpeg"pageEncoding="gb2312"%>
<%@ page import="java.awt.*,java.awt.image.*"%>
<%@ page import="java.util.*,javax.imageio.*"%>
<%!
//產(chǎn)生隨機(jī)顏色函數(shù)getRandColor
Color getRandColor(int fc,int bc){
Random r=new Random();
if(fc>255) fc=255;
if(bc>255) bc=255;
int red=fc+r.nextInt(bc-fc); //red
int green=fc+r.nextInt(bc-fc); //green
int blue=fc+r.nextInt(bc-fc); //blue
return new Color(red,green,blue);
}
%>
<%
//設(shè)置頁面不緩存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
//創(chuàng)建隨機(jī)類
Random r=new Random();
//在內(nèi)存中創(chuàng)建圖像,寬度為width,高度為height
int width=60,height=20;
BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//獲取圖形上下文環(huán)境
Graphics gc=pic.getGraphics();
//設(shè)定背景圖形上下文填充
gc.setColor(getRandColor(200,250));
gc.fillRect(0,0,width,height);
//設(shè)定圖形上下文環(huán)境字體
gc.setFont(new Font("Times New Roman",Font.PLAIN,18));
//隨機(jī)產(chǎn)生200條干擾直線,使圖像中的認(rèn)證碼不易被其他分析程序探測(cè)
gc.setColor(getRandColor(160,200));
for(int i=0;i<200;i++){
int x1=r.nextInt(width);
int y1=r.nextInt(height);
int x2=r.nextInt(15);
int y2=r.nextInt(15);
gc.drawLine(x1,y1,x1+x2,y1+y2);
}
//隨機(jī)產(chǎn)生100個(gè)干擾點(diǎn),使圖像中的驗(yàn)證碼不易被其他分析程序探測(cè)到
gc.setColor(getRandColor(120,240));
for(int i=0;i<100;i++)
{
int x=r.nextInt(width);
int y=r.nextInt(height);
gc.drawOval(x,y,0,0);
}
//隨機(jī)產(chǎn)生4位數(shù)字的驗(yàn)證碼
String RS="";
String rn="";
for(int i=0;i<4;i++){
//產(chǎn)生10以內(nèi)的隨機(jī)數(shù)字rn
rn=String.valueOf(r.nextInt(10));
RS+=rn;
//將認(rèn)證碼用drawString函數(shù)顯示到圖像里
gc.setColor(new
Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));
gc.drawString(rn,13*i+6,16);
}
//釋放圖形上下文環(huán)境
gc.dispose();
//將認(rèn)證碼RS存入SESSION中共享
session.setAttribute("random",RS);
//輸出生成后的驗(yàn)證碼圖像到頁面
ImageIO.write(pic,"jpeg",response.getOutputStream());
%>
效果圖如下: