Java web实现动态图片验证码的示例代码
验证码
防止恶意表单注册
生成验证码图片
定义宽高
int width = 100; int height = 50;
使用BufferedImage再内存中生成图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
绘制背景和边框
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);
创建随机字符集和随机数对象
//字符集 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjijklmnopqrstuvwxyz"; //随机数 Random ran = new Random();
创建随机颜色生成方法
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;
}
}
绘制验证码字符
//绘制验证码
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);
}
绘制干扰线
//干扰线
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);
}
使用ImageIO输出图片
ImageIO.write(image, "jpg", resp.getOutputStream());
成果图

实现刷新效果
新建html页面
使用img标签实现图片展示
<img id="identcode" src="identcode"> <a id="refesh" href="">看不清,换一张</a>
使用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;
}
效果


项目源码
https://github.com/xiaochen0517/StudySpace/tree/master/idea/TestDemo3
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Hadoop MultipleOutputs输出到多个文件中的实现方法
这篇文章主要介绍了 Hadoop MultipleOutputs输出到多个文件中的实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下2017-10-10
SpringBoot应用启动失败:端口占用导致Tomcat启动失败的问题分析与解决方法
在开发和运维过程中,应用程序启动失败是我们经常遇到的一个问题,尤其是在 Web 应用程序中,涉及到 Web 服务器的配置时,今天我们将探讨一个常见的启动错误,尤其是在使用 Spring Boot 和内嵌 Tomcat 服务器时,需要的朋友可以参考下2024-11-11
Hibernate用ThreadLocal模式(线程局部变量模式)管理Session
今天小编就为大家分享一篇关于Hibernate用ThreadLocal模式(线程局部变量模式)管理Session,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2019-03-03
SpringValidation数据校验之约束注解与分组校验方式
本文将深入探讨Spring Validation的核心功能,帮助开发者掌握约束注解的使用技巧和分组校验的高级应用,从而构建更加健壮和可维护的Java应用程序,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-04-04


最新评论