java生成图片验证码功能
最近在用ssm框架做一个管理系统,做到登录验证时,使用了下面的代码生成图片验证码,最终的效果如下图。
Java类
publicclassRandomValidateCode{
publicstaticfinalStringRANDOMCODEKEY="randomcode_key";//放到session中的key
privateRandomrandom=newRandom();
privateStringrandString="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
privateintwidth=80;//图片宽
privateintheight=26;//图片高
privateintlineSize=40;//干扰线数量
privateintstringNum=4;//随机产生字符数量
/**
*生成随机图片
*/
publicvoidgetRandcode(HttpServletRequestrequest,
HttpServletResponseresponse){
HttpSessionsession=request.getSession();
//BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
Graphicsg=image.getGraphics();
g.fillRect(0,0,width,height);
g.setFont(newFont("TimesNewRoman",Font.ROMAN_BASELINE,18));
g.setColor(getRandColor(160,200));
//绘制干扰线
for(inti=0;i<=lineSize;i++){
drowLine(g);
}
//绘制随机字符
StringrandomString="";
for(inti=1;i<=stringNum;i++){
randomString=drowString(g,randomString,i);
}
session.removeAttribute(RANDOMCODEKEY);
session.setAttribute(RANDOMCODEKEY,randomString);
g.dispose();
try{
//将内存中的图片通过流动形式输出到客户端
ImageIO.write(image,"JPEG",response.getOutputStream());
}catch(Exceptione){
e.printStackTrace();
}
}
/*
*获得字体
*/
privateFontgetFont(){
returnnewFont("Fixedsys",Font.CENTER_BASELINE,18);
}
/*
*获得颜色
*/
privateColorgetRandColor(intfc,intbc){
if(fc>255)
fc=255;
if(bc>255)
bc=255;
intr=fc+random.nextInt(bc-fc-16);
intg=fc+random.nextInt(bc-fc-14);
intb=fc+random.nextInt(bc-fc-18);
returnnewColor(r,g,b);
}
/*
*绘制字符串
*/
privateStringdrowString(Graphicsg,StringrandomString,inti){
g.setFont(getFont());
g.setColor(newColor(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
Stringrand=String.valueOf(getRandomString(random.nextInt(randString.length())));
randomString+=rand;
g.translate(random.nextInt(3),random.nextInt(3));
g.drawString(rand,13*i,16);
returnrandomString;
}
/*
*绘制干扰线
*/
privatevoiddrowLine(Graphicsg){
intx=random.nextInt(width);
inty=random.nextInt(height);
intxl=random.nextInt(13);
intyl=random.nextInt(15);
g.drawLine(x,y,x+xl,y+yl);
}
/*
*获取随机的字符
*/
publicStringgetRandomString(intnum){
returnString.valueOf(randString.charAt(num));
}
}
Controller
@RequestMapping(value="/checkCode")
publicvoidcheckCode(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//设置相应类型,告诉浏览器输出的内容为图片
response.setContentType("image/jpeg");
//设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expire",0);
RandomValidateCoderandomValidateCode=newRandomValidateCode();
try{
randomValidateCode.getRandcode(request,response);//输出图片方法
}catch(Exceptione){
e.printStackTrace();
}
}
前端jsp页面表单,显示验证码
