Java web实现动态图片验证码的示例代码
验证码
防止恶意表单注册
生成验证码图片
定义宽高
intwidth=100; intheight=50;
使用BufferedImage再内存中生成图片
BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
绘制背景和边框
Graphicsg=image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0,0,width,height); g.setColor(Color.BLACK); g.drawRect(0,0,width-1,height-1);
创建随机字符集和随机数对象
//字符集 Stringstr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjijklmnopqrstuvwxyz"; //随机数 Randomran=newRandom();
创建随机颜色生成方法
privateColorgetRandomColor(Randomrandom){
//获取随机颜色
intcolorIndex=random.nextInt(3);
switch(colorIndex){
case0:
returnColor.BLUE;
case1:
returnColor.GREEN;
case2:
returnColor.RED;
case3:
returnColor.YELLOW;
default:
returnColor.MAGENTA;
}
}
绘制验证码字符
//绘制验证码
for(inti=0;i<4;i++){
//获取随机字符
intindex=ran.nextInt(str.length());
charch=str.charAt(index);
//获取随机色
ColorrandomColor=getRandomColor(ran);
g.setColor(randomColor);
//设置字体
Fontfont=newFont("宋体",Font.BOLD,height/2);
g.setFont(font);
//写入验证码
g.drawString(ch+"",(i==0)?width/4*i+2:width/4*i,height-height/4);
}
绘制干扰线
//干扰线
for(inti=0;i<10;i++){
intx1=ran.nextInt(width);
intx2=ran.nextInt(width);
inty1=ran.nextInt(height);
inty2=ran.nextInt(height);
ColorrandomColor=getRandomColor(ran);
g.setColor(randomColor);
g.drawLine(x1,x2,y1,y2);
}
使用ImageIO输出图片
ImageIO.write(image,"jpg",resp.getOutputStream());
成果图
实现刷新效果
新建html页面
使用img标签实现图片展示
看不清,换一张
使用js实现刷新效果
//点击图片时
varimg=document.getElementById("http://dh.wk163.comidentcode");
img.onclick=function(){
refesh();
}
//点击连接时
vara=document.getElementById("refesh");
a.onclick=function(){
refesh();
//返回false防止a标签默认href行为
returnfalse;
}
functionrefesh(){
/**
*由于路径相同时浏览器会自动调用缓存中的图片
*所以在连接后加时间戳解决此问题
*/
vardate=newDate().getTime();
img.src="http://dh.wk163.comidentcode?"+date;
}
效果
项目源码
https://github.com/xiaochen0517/StudySpace/tree/master/idea/TestDemo3
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。