java绘制图片验证码(看不清,换一张)

现在正式开发中图片验证码好像已经很少用了,但是为了加深个人印象,做个小笔记。

验证码实现分析

  1. 在用java生成一张固定尺寸的图片,会用到api是BufferedImage(int width,int height,int type);
  2. 给图片上绘制出随机的文字、字母或者数字,用到API是Graphics2D(绘制文字)和Random(生成随机数)
  3. 绘制随机的干扰线用到Api为graphics2d.drawLine(x1, y1, x2, y2);
  4. 将图片展示到浏览器上用到Api为 ImageIO

生成图片的具体java代码如下


/*** @author jiangrongtao 图片验证码*/
public class VerificationCodeUtils {private static List colors;static{colors=new ArrayList<>();colors.add(Color.CYAN);colors.add(Color.yellow);colors.add(Color.PINK);colors.add(Color.green);}/*** 1、绘制图片 2、给图片上随机绘制文字 3、随机绘制干扰线4、将图片绘制到浏览器* @param response HttpServletResponse* @param width  图片宽度* @param height 图片高度* @param fontNum 数字个数* @return 返回随机生成的验证码*/public static String drawVerificationCode(HttpServletResponse response, int width, int height,int fontNum) {/*** 生成图片*/BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);// 绘制文字Graphics2D graphics2d = bufferedImage.createGraphics();graphics2d.setFont(new Font("华文行楷", Font.ITALIC | Font.BOLD, 20));// 设置字体样式String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";StringBuilder sb=new StringBuilder();// 随机取四个值Random random = new Random();for (int i = 1; i <= fontNum; i++) {char ch = words.charAt(random.nextInt(words.length()));graphics2d.setColor(getColor(random));// 设置字体颜色graphics2d.drawString(ch + "", (width/fontNum)*i-30, height/2+10);sb.append(ch);}//绘制干扰线for (int i = 0; i <5; i++) {graphics2d.setColor(getColor(random));int x1=random.nextInt(width);int x2=random.nextInt(width);int y1=random.nextInt(height);int y2=random.nextInt(height);graphics2d.drawLine(x1, y1, x2, y2);    }try {ImageIO.write(bufferedImage, "jpg", response.getOutputStream());} catch (IOException e) {e.printStackTrace();}return sb.toString();}/*** 随机获取一种颜色* @param random* @return Color*/private static Color getColor(Random random){return random==null?null:colors.get(random.nextInt(4));}
}

在具体用的时候直接

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String code=VerificationCodeUtils.drawVerificationCode(resp,160,40,4);System.out.println("code="+code);}

这里我打印出了随机生成的验证码,实际开发中可以把这个存到数据库来跟客户端提交的验证码进行比对验证

实现”看不清,换一张“

这里可以用js或者ajax实习异步局部刷新,具体如下

js实现如下:


<html>
<head>
<meta charset="UTF-8">
<title>验证码title>
head>
<body><form action="/MyWebTest/login" method="post"><img id="_img" alt="" src="/MyWebTest/verifyCode"><a href="#" onclick="changeCode();">看不清,换一张a><br/>form><script type="text/javascript">function changeCode(){var img=document.getElementById("_img");img.src="/MyWebTest/verifyCode?"+new Date().getTime();}script>
body>
html>

Jquery方式实现


<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="js/jquery-3.2.1.min.js">script>
<title>验证码title>
head>
<body><form action="/MyWebTest/login" method="post"><img id="_img" alt="" src="/MyWebTest/verifyCode"><a href="#">看不清,换一张a><br/>form><script type="text/javascript">$(document).ready(function () {  $("a").click(function() {var src= $("#_img").attr("src","/MyWebTest/verifyCode?"+new Date().getTime());});});script>
body>
html>

注意:

  1. a标签中的href属性值用”#“号占位,如果用”javascript:void(0)“的话会出现IO异常。
  2. 给”/MyWebTest/verifyCode”后面拼接new Date().getTime())参数是为了防止浏览器缓存导致验证码不刷新;
  3. 用jQuery的时候导入对应的js库文件
<script type="text/javascript" src="http://xxxx/jquery-3.2.1.min.js">script>

总结

  学一点,总结一点,每天提升一点。


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部