您好,欢迎访问一九零五行业门户网

java实现动态图片验证码

目的:
防止恶意表单注册
生成验证码图片
1、定义宽高
int width = 100;int height = 50;
2、使用bufferedimage在内存中生成图片
bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb);
3、绘制背景和边框
graphics g = image.getgraphics();g.setcolor(color.white);g.fillrect(0, 0, width, height);g.setcolor(color.black);g.drawrect(0, 0, width - 1, height - 1);
(免费学习视频教程分享:java视频教程)
4、创建随机字符集和随机数对象
//字符集string str = "abcdefghijklmnopqrstuvwxyzabcdefgjijklmnopqrstuvwxyz";//随机数random ran = new random();
5、创建随机颜色生成方法
private color getrandomcolor(random random) { //获取随机颜色 int colorindex = random.nextint(3); switch (colorindex) { case 0: return color.blue; case 1: return color.green; case 2: return color.red; case 3: return color.yellow; default: return color.magenta; }}
6、绘制验证码字符
//绘制验证码for (int i = 0; i < 4; i++) { //获取随机字符 int index = ran.nextint(str.length()); char ch = str.charat(index); //获取随机色 color randomcolor = getrandomcolor(ran); g.setcolor(randomcolor); //设置字体 font font = new font("宋体", font.bold, height / 2); g.setfont(font); //写入验证码 g.drawstring(ch + "", (i == 0) ? width / 4 * i + 2 : width / 4 * i, height - height / 4);}
7、绘制干扰线
//干扰线for (int i = 0; i < 10; i++) { int x1 = ran.nextint(width); int x2 = ran.nextint(width); int y1 = ran.nextint(height); int y2 = ran.nextint(height); color randomcolor = getrandomcolor(ran); g.setcolor(randomcolor); g.drawline(x1, x2, y1, y2);}
8、使用imageio输出图片
imageio.write(image, "jpg", resp.getoutputstream());
实现刷新效果
1、新建html页面
2、使用img标签实现图片展示
<img id="identcode" src="identcode"><a id="refesh" href="">看不清,换一张</a>
3、使用js实现刷新效果
//点击图片时var img = document.getelementbyid("identcode");img.onclick = function (){ refesh();}//点击连接时var a = document.getelementbyid("refesh");a.onclick = function (){ refesh(); //返回false防止a标签默认href行为 return false;}function refesh() { /** * 由于路径相同时浏览器会自动调用缓存中的图片 * 所以在连接后加时间戳解决此问题 */ var date = new date().gettime(); img.src = "identcode?" + date;}
最终效果图:
相关文章教程推荐:java入门教程
以上就是java实现动态图片验证码的详细内容。
其它类似信息

推荐信息