生成base64格式图片验证码

 /**
* 验证码的候选内容
*/
private char codeSequence[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  /**
* 生成验证码
* 改造生成验证码的方式,将图片base64形式传到前台,而不是直接传验证码到前台
* @return
* @throws IOException
*/
public void imageCode() throws IOException {
HttpServletResponse resp = CommandContext.getResponse();
HttpServletRequest req = CommandContext.getRequest();
String method= req.getMethod();
if("OPTIONS".equals(method)){
return ;
}
Map map=new HashMap(); // 在内存中创建图象
int width = 65, height = 38;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(230, 255));
g.fillRect(0, 0, 100, 40);
// 设定字体
g.setFont(new Font("Arial", Font.CENTER_BASELINE | Font.ITALIC, 20));
// 产生0条干扰线,
g.drawLine(0, 0, 0, 0); //存放验证码
StringBuffer sRand = new StringBuffer();
for (int i = 0; i < charCount; i++) {
String singleCode = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
sRand.append(singleCode);
// 将认证码显示到图象中
g.setColor(getRandColor(100, 150));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(singleCode, 14 * i + 5, 25);
}
for(int i=0;i<(random.nextInt(5)+5);i++){
g.setColor(new Color(random.nextInt(255)+1,random.nextInt(255)+1,random.nextInt(255)+1));
g.drawLine(random.nextInt(70),random.nextInt(40),random.nextInt(70),random.nextInt(40));
g.drawLine(random.nextInt(70),random.nextInt(40),random.nextInt(70),random.nextInt(40));
} HttpSession session = req.getSession();
//获取clientid
String clientId= SystemUtil.getClientId(req);
if(StringUtils.isEmpty(clientId)){
//生成clientid
String userAgent=req.getHeader("User-Agent");
String sessionId=session.getId();
String cip= IpPolicy.getClientIP(req);
clientId=CodeUtil.genClientId(sessionId,cip,userAgent);
}
map.put("clientId", clientId);
if (isValidateCodeCaseSensitive) {
session.setAttribute("randomCode", sRand.toString());
SystemUtil.push2Cache(clientId, sRand.toString());
} else {
session.setAttribute("randomCode", sRand.toString().toLowerCase());
SystemUtil.push2Cache(clientId, sRand.toString().toLowerCase());
}
// 图象生效
g.dispose();
try{ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
BASE64Encoder encoder = new BASE64Encoder();
String base64Img = encoder.encode(outputStream.toByteArray());
base64Img="data:image/jpg;base64, "+base64Img.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n;
map.put("verCode", base64Img);
Object jsonObj = JSONSerializer.toJSON(map);
byte[] json = jsonObj.toString().getBytes("UTF-8");
resp.setContentType("text/plain;chartset=utf-8");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Expires", "0");
resp.setIntHeader("Content-Length", json.length);
ServletOutputStream responseOutputStream = resp.getOutputStream();
responseOutputStream.write(json);
// 以下关闭输入流!
responseOutputStream.flush();
responseOutputStream.close();
// 获得页面key值
return ;
} catch (IOException e) {
logger.error("生产验证码出错",e);
throw new SystemException("生产验证码出错",e);
}
} /**
* 给定范围获得随机颜色
*
* @param fc
* @param bc
* @return
*/
Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}

JAVA生成验证码代码的更多相关文章

  1. 【开发技术】Java生成验证码

    Java生成验证码 为了防止用户恶意,或者使用软件外挂提交一些内容,就得用验证码来阻止,虽然这个会影响用户体验,但为了避免一些问题很多网站都使用了验证码;今天下午参考文档弄了一个验证码,这里分享一下; ...

  2. Java生成验证码原理(jsp)

     验证码的作用: 验证码是Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的 ...

  3. Java生成验证码并进行验证(转)

    本文转自http://blog.csdn.net/worm0527/article/details/51030864 一.实现思路 使用BufferedImage用于在内存中存储生成的验证码图片 使用 ...

  4. Java生成验证码_转

    为了防止用户恶意,或者使用软件外挂提交一些内容,就得用验证码来阻止,虽然这个会影响用户体验,但为了避免一些问题很多网站都使用了验证码;今天下午参考文档弄了一个验证码,这里分享一下;这是一个web工程, ...

  5. java生成验证码结合springMVC

    在用户登录的时候,为了防止机器人攻击都会设置输入验证码,本篇文章就是介绍java如何生成验证码并使用在springMVC项目中的. 第一步:引入生成图片验证码的工具类 import java.awt. ...

  6. Java生成验证码(二)

    前一篇博客已经介绍了如何用Java servlet产生验证码,本篇继续介绍如何使用一些开源组件生成验证码 ————————————————————————————————————————————   ...

  7. java生成验证码并可刷新

    手心创建一个简单的页面来显示所创建的验证码 <body> <form action="loginName.mvc" method="post" ...

  8. Java 生成验证码图片

    生成验证码图片并对提交的输入进行验证 // HttpServletResponse常见应用——生成验证码 // 利用BufferedImage类生产随机图片 public static final i ...

  9. Java生成验证码小工具

    无意中看到一个生成简易验证码的小工具类(保存学习): 工具类代码: import java.awt.BasicStroke; import java.awt.Color; import java.aw ...

随机推荐

  1. WIN7+Qt5.2.0连接oracle数据库的oci驱动的编译

    一.前提安装 1.需要安装QT5.2.0,本介绍安装的是qt-windows-opensource-5.2.0-mingw48_opengl-x86-offline.exe: 本文安装目录:c:\Qt ...

  2. ailoop2里面的1个待考察的,在ailoop3里面的操作。(先使用海巨人,不使用英雄技能召唤图腾的问题)

    承接上一篇博客HearthBuddy Ai 调试实战2 在使用海巨人的时候,少召唤了一个图腾(费用是对的) 研究ailoop2里面4个待考察的,在ailoop3里面的后续操作.ailoop3一共有36 ...

  3. 美国top200药品2

     python机器学习-乳腺癌细胞挖掘(博主亲自录制视频)https://study.163.com/course/introduction.htm?courseId=1005269003&u ...

  4. C#与C++数据类型对应表(搜集整理一)

    C#与C++数据类型对应表(搜集整理一) C#与C++数据类型对应表   C#调用DLL文件时参数对应表 Wtypes.h 中的非托管类型 非托管 C 语言类型 托管类名 说明 HANDLE void ...

  5. 用ConfigMap管理配置(10)

    一.ConfigMap介绍管理配置:   ConfigMap介绍 Secret 可以为 Pod 提供密码.Token.私钥等敏感数据:对于一些非敏感数据,比如应用的配置信息,则可以用 ConfigMa ...

  6. Python的数据类型与数据结构

    Python的数据类型与数据结构 数据类型分为: 整数型 :数字的整数 浮点型: 数字带小数 字符串: 用 ‘’ 或者 “” 引用的任意文本 布尔型:只有 True 和 False 数据结构分为: 列 ...

  7. postman使用当前时间戳

    //设置当前时间戳postman.setGlobalVariable(“time”,Math.round(new Date().getTime()));time = postman.getGlobal ...

  8. Java连接阿里云HBase示例

    使用前要在阿里云的 HBase控制台中点击"修改网络白名单",然后将你的ip地址(会有提示的)添加到网络白名单中,这样以后才能访问. 所需依赖: <dependencies& ...

  9. web布局收集整理

    /*样式文件*/ .fgw-right-p{ height: 38px; line-height: 38px; margin-bottom: 20px; padding-left: 24px; spa ...

  10. java8:(Lambda 表达式简介)

    JDK8的新特性——Lambda表达式 JDK8已经发布快4年的时间了,现在来谈它的新特性显得略微的有点“不合时宜”.尽管JDK8已不再“新”,但它的重要特性之一——Lambda表达式依然是不被大部分 ...