目的:
防止恶意表单注册
生成验证码图片
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实现动态图片验证码的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)