[前言]:图片验证在有关注册和发表留言经常用到我在此用jsp写了个供大家参考 其中 comsunimage 不是java的标准包需要另外下载相关地址为
http://javasuncom/products/javamedia/jai/
randomjsp (产生四位的随机字符由azAZ构成并把最终字符串放到session中保存以让后续页面验证真伪)
代码如下
<%@ page autoFlush=false import=javautil*javaawt*javaawtimage*
comsunimagecodecjpeg*javautil*%>
<%@ page import= contentType=text/html; charset=gb%>
<%
String chose=
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;
char display[]={ }ran[]={}temp;
Random rand=new Random();
for(int i=;i<;i++)
{
temp=chosecharAt(randnextInt(choselength()));
display[i*]=temp;
ran[i]=temp;
}
String random=StringvalueOf(display);
sessionsetAttribute(randomStringvalueOf(ran));
%>
<%
outclear();
responsesetContentType(image/jpeg);
responseaddHeader(pragmaNOcache);
responseaddHeader(CacheControlnocache);
responseaddDateHeader(Expries);
int width= height=;
BufferedImage image = new BufferedImage(width height BufferedImageTYPE_INT_RGB);
Graphics g = imagegetGraphics();
//以下填充背景颜色
gsetColor(ColorGREEN);
gfillRect( width height);
//设置字体颜色
gsetColor(ColorRED);
gdrawString(random);
gdispose();
ServletOutputStream outStream = responsegetOutputStream();
JPEGImageEncoder encoder =JPEGCodeccreateJPEGEncoder(outStream);
encoderencode(image);
outStreamclose();
%>
[] []