生成随街验证码

VerifyCode 工具类

package com.meeno.common.cerifycode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random; /**
* @description: 随机验证码
* @author: Wzq
* @create: 2020-09-08 16:55
*/
public class VerifyCode { private int w=70;
private int h=35;
private Random r= new Random(); private String[] fontNames={"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312"};
private String codes="012345678901234567890123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
private Color bgColor = new Color(255,255,255);
private String text; private Color randomColor(){
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red,green,blue);
} private Font randomFont(){
int index = this.r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = this.r.nextInt(4);
int size = this.r.nextInt(5) + 24;
return new Font(fontName, style, size);
} private void drawLine (BufferedImage image){
int num = 3;
Graphics2D g2=(Graphics2D)image.getGraphics();
for(int i=0;i<num;i++){
int x1=r.nextInt(w);
int y1=r.nextInt(h);
int x2=r.nextInt(w);
int y2=r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
g2.setColor(Color.BLUE);
g2.drawLine(x1,y1,x2,y2);
} } private char randomChar(){
int index=r.nextInt(this.codes.length());
return this.codes.charAt(index);
} private BufferedImage createImage(){
BufferedImage image=new BufferedImage(this.w,this.h,BufferedImage.TYPE_INT_RGB);//BufferedImage.TYPE_INT_RGB
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setColor(this.bgColor);
g2.fillRect(0,0,this.w,this.h);
return image;
} public BufferedImage getImage(){
BufferedImage image=createImage();
Graphics2D g2=(Graphics2D)image.getGraphics();
StringBuilder sb = new StringBuilder();
for(int i =0;i<4;i++){
String s= randomChar()+"";
sb.append(s);
float x= i*1.0F*this.w/4.0F;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s,x,this.h-5);
}
this.text=sb.toString();
drawLine(image);//添加干扰线
return image;
}
//返回验证码上的文本
public String getText(){
return this.text; }
//保存图片到指定的输出流
public static void output(BufferedImage image, OutputStream out)
throws IOException {
ImageIO.write(image,"JPEG",out); } public static void main(String[] args) throws IOException {
VerifyCode vc=new VerifyCode();
BufferedImage bi = vc.getImage();
VerifyCode.output(bi,new FileOutputStream("E:\\work\\temp\\xxx.jpg")); System.out.println("图片中的验证是:"+vc.getText()); } }

使用


/**
* 生成随机验证码
*/
@RequestMapping("randomVerifyCode.do")
public ResponseBean randomVerifyCode() throws IOException {
VerifyCode vc = new VerifyCode();
BufferedImage bi = vc.getImage();
//VerifyCode.output(bi,response.getOutputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "png", out);
byte[] bytes = out.toByteArray(); String str = Base64.encode(bytes);
str = "data:image/png;base64," + str; String uuid = IdUtil.simpleUUID(); Map<String,String> resultMap = Maps.newHashMap();
resultMap.put("base64", str);
resultMap.put("uuid", uuid); //save redis
String key = "RandomVerify:" + uuid;
RedisUtil.set(key, vc.getText(), 180); return ResultUtil.success(resultMap);
}

验证方法

 /**
* 账号登录
* @param session
* @param phone
* @param pwd
* @param entryType
* @return
*/
@RequestMapping("accountLogin.do")
public ResponseBean accountLogin(final HttpSession session, String phone, String pwd, String entryType,
String uuid, String randomCerifyCode){ //校验验证码
MeenoAssert.hasLength(randomCerifyCode,"randomCerifyCode can not empty!");
Object randomCerifyCodeObj = RedisUtil.get("RandomVerify:" + uuid); MeenoAssert.notNull(randomCerifyCodeObj, CErrEnum.RANDOM_VERIFY_CODE_FAILURE);
MeenoAssert.isTrue(randomCerifyCode.toLowerCase().equals(randomCerifyCodeObj.toString().toLowerCase()), CErrEnum.RANDOM_VERIFY_CODE_ERR); LoginResult loginResult = this.employeeService.accountLogin(session, phone, pwd, entryType);
EmpView employeeView = this.employeeService.getEmployee(loginResult.getUserInfo().getId()); Map<String,Object> resultMap = Maps.newHashMap();
resultMap.put("loginResult", loginResult);
resultMap.put("employee", employeeView); return ResultUtil.success(resultMap);
}

java实现随机字母数字验证码的更多相关文章

  1. 007-TreeMap、Map和Bean互转、BeanUtils.copyProperties(A,B)拷贝、URL编码解码、字符串补齐,随机字母数字串

    一.转换 1.1.TreeMap 有序Map 无序有序转换 使用默认构造方法: public TreeMap(Map<? extends K, ? extends V> m) 1.2.Ma ...

  2. canvas验证码 - 随机字母数字

    基于canvas制作随机生成数字英文组合验证码效果,点击或刷新会自动重组.输入验证码提交验证效果代码. <div class="verification"> <i ...

  3. PHP字母数字验证码和中文验证码

    1:字母数字组合的验证码 HTML代码: 验证码:<input type="text" name="code"> <img onclick=& ...

  4. 字母数字、字母、汉字验证码 (java)

    原文:http://blog.csdn.net/qh_java/article/details/49854477 一.字母数字,字母,汉字验证码的生成代码 1.字母数字验证码: package com ...

  5. php生成纯数字、字母数字、图片、纯汉字的随机数验证码

    现在讲开始通过PHP生成各种验证码旅途,新手要开车了,请刷卡! 首先,我们开始先生成一个放验证码的背景图片 注:没有Imagejpg()这个函数,只有imagepng()函数 imagecreatet ...

  6. JS生成随机的由字母数字组合的字符串

    前言 最近有个需求,是需要生成3-32位长度的字母数字组合的随机字符串,另一个是生成43位随机字符串. 方法一 奇妙的写法   1 Math.random().toString(36).substr( ...

  7. js随机生成字母数字组合的字符串 随机动画数字

    效果描述: 附件中只有一个index.html文件有效 其中包含css以及html两部分内容 纯js生成的几个随机数字 每次都不重复,点击按钮后再次切换 使用方法: 1.将css样式引入到你的网页中 ...

  8. php实现随机数字、字母的验证码

     php实现随机数字.字母的验证码 可自定义生成验证码文字的大小.数量.干扰项等等,也可以自定义验证文字的字体... 废话不多说,直接上代码: 1.classgd.class.php <?php ...

  9. JavaScript 编写随机四位数验证码(大小写字母和数字)

    1.JavaScript编写随机四位数验证码,用到的知识点为: a.Math对象的随机数:Math.random() b.Math对象的取整    :Math.floor() c.处理所需要的下标个数 ...

随机推荐

  1. phpstudy后门复现遇到的坑

    这几天遇到一个phpstudy后门的站之前没复现过,结果遇到了深坑记录一下 首先用这个脚本去验证是没问题的: https://github.com/NS-Sp4ce/PHPStudy_BackDoor ...

  2. ES异地双活方案

    对于单机房而言,只要参考Elastic Search 官方文档,搭建一个集群即可,示意图如下: 原理类似分布式选举那一套,当一个master节点宕机时,剩下2个投票选出1个新老大,整个集群可以继续服务 ...

  3. C语言:extern应用

    前面我们都是将所有的代码写到一个源文件里面,对于小程序,代码不过几百行,这或许无可厚非,但当程序膨胀代码到几千行甚至上万行后,就应该考虑将代码分散到多个文件中,否则代码的阅读和维护将成为一件痛苦的事情 ...

  4. YARN学习总结之架构

    一.yarn产生背景 1) 源于MRv1的缺陷:扩展性受限.单点故障.难以支持MR之外的计算框架: 2) 多计算框架各自为战,数据共享困难,资源利用率低: MR: 离线计算框架 Storm:实时计算框 ...

  5. C标准库学习

    前言 C标准库源码可通过下列两个网站进行查看:The GNU C Library.Welcome to uClibc-ng! - Embedded C library 以下学习记录也是以这两个网站提供 ...

  6. JAVA-Scaneer对象

    Scanner对象 我们可以通过scanner来获取用户的输入 基本语法 Scanner s = new Scanner(System.in); nextLine():输入 import java.u ...

  7. Bootstrap框架--DataTables列表示例--添加判断

    一.参考代码 <%@ include file="./include/header.jsp"%> <!-- jquery.dataTables.css --> ...

  8. odoo里的开发案例

    1.模块命名[驼峰命名方法] res开头的是:resources   常见模型:res.users,   res.company,    res.partner,   res.config.setti ...

  9. Windows下删除顽固文件夹

    参考链接: https://www.cnblogs.com/azbane/p/9808802.html 第一步:修改当前文件夹所有者为管理员 takeown /f * /a /r 第二步:修改管理员权 ...

  10. 利用docker-compose快速部署测试用数据库服务器

    起因 开发中经常需要快速部署一台随用随关的数据库服务器,如mysql,oracle,mongodb,elastic-search 尝试 一直觉得docker特别方便,加上docker-compose. ...