java中生成验证码,以及验证码的使用:

1:验证码生成工具类:

  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics;
  4. import java.awt.Graphics2D;
  5. import java.awt.RenderingHints;
  6. import java.awt.geom.AffineTransform;
  7. import java.awt.image.BufferedImage;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStream;
  12. import java.util.Arrays;
  13. import java.util.Random;
  14.  
  15. import javax.imageio.ImageIO;
  16. /**
  17. * <p><b>VerifyCodeUtils Description:</b> (验证码生成)</p>
  18. * <b>DATE:</b> 2016年6月2日 下午3:53:34
  19. */
  20. public class VerifyCodeUtils{
  21.  
  22. //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
  23. public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  24. private static Random random = new Random();
  25.  
  26. /**
  27. * 使用系统默认字符源生成验证码
  28. * @param verifySize 验证码长度
  29. * @return
  30. */
  31. public static String generateVerifyCode(int verifySize){
  32. return generateVerifyCode(verifySize, VERIFY_CODES);
  33. }
  34. /**
  35. * 使用指定源生成验证码
  36. * @param verifySize 验证码长度
  37. * @param sources 验证码字符源
  38. * @return
  39. */
  40. public static String generateVerifyCode(int verifySize, String sources){
  41. if(sources == null || sources.length() == 0){
  42. sources = VERIFY_CODES;
  43. }
  44. int codesLen = sources.length();
  45. Random rand = new Random(System.currentTimeMillis());
  46. StringBuilder verifyCode = new StringBuilder(verifySize);
  47. for(int i = 0; i < verifySize; i++){
  48. verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
  49. }
  50. return verifyCode.toString();
  51. }
  52.  
  53. /**
  54. * 生成随机验证码文件,并返回验证码值
  55. * @param w
  56. * @param h
  57. * @param outputFile
  58. * @param verifySize
  59. * @return
  60. * @throws IOException
  61. */
  62. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
  63. String verifyCode = generateVerifyCode(verifySize);
  64. outputImage(w, h, outputFile, verifyCode);
  65. return verifyCode;
  66. }
  67.  
  68. /**
  69. * 输出随机验证码图片流,并返回验证码值
  70. * @param w
  71. * @param h
  72. * @param os
  73. * @param verifySize
  74. * @return
  75. * @throws IOException
  76. */
  77. public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
  78. String verifyCode = generateVerifyCode(verifySize);
  79. outputImage(w, h, os, verifyCode);
  80. return verifyCode;
  81. }
  82.  
  83. /**
  84. * 生成指定验证码图像文件
  85. * @param w
  86. * @param h
  87. * @param outputFile
  88. * @param code
  89. * @throws IOException
  90. */
  91. public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
  92. if(outputFile == null){
  93. return;
  94. }
  95. File dir = outputFile.getParentFile();
  96. if(!dir.exists()){
  97. dir.mkdirs();
  98. }
  99. try{
  100. outputFile.createNewFile();
  101. FileOutputStream fos = new FileOutputStream(outputFile);
  102. outputImage(w, h, fos, code);
  103. fos.close();
  104. } catch(IOException e){
  105. throw e;
  106. }
  107. }
  108.  
  109. /**
  110. * 输出指定验证码图片流
  111. * @param w
  112. * @param h
  113. * @param os
  114. * @param code
  115. * @throws IOException
  116. */
  117. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
  118. int verifySize = code.length();
  119. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  120. Random rand = new Random();
  121. Graphics2D g2 = image.createGraphics();
  122. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  123. Color[] colors = new Color[5];
  124. Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
  125. Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
  126. Color.PINK, Color.YELLOW };
  127. float[] fractions = new float[colors.length];
  128. for(int i = 0; i < colors.length; i++){
  129. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  130. fractions[i] = rand.nextFloat();
  131. }
  132. Arrays.sort(fractions);
  133.  
  134. g2.setColor(Color.GRAY);// 设置边框色
  135. g2.fillRect(0, 0, w, h);
  136.  
  137. Color c = getRandColor(200, 250);
  138. g2.setColor(c);// 设置背景色
  139. g2.fillRect(0, 2, w, h-4);
  140.  
  141. //绘制干扰线
  142. Random random = new Random();
  143. g2.setColor(getRandColor(160, 200));// 设置线条的颜色
  144. for (int i = 0; i < 20; i++) {
  145. int x = random.nextInt(w - 1);
  146. int y = random.nextInt(h - 1);
  147. int xl = random.nextInt(6) + 1;
  148. int yl = random.nextInt(12) + 1;
  149. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  150. }
  151.  
  152. // 添加噪点
  153. float yawpRate = 0.05f;// 噪声率
  154. int area = (int) (yawpRate * w * h);
  155. for (int i = 0; i < area; i++) {
  156. int x = random.nextInt(w);
  157. int y = random.nextInt(h);
  158. int rgb = getRandomIntColor();
  159. image.setRGB(x, y, rgb);
  160. }
  161.  
  162. shear(g2, w, h, c);// 使图片扭曲
  163.  
  164. g2.setColor(getRandColor(100, 160));
  165. int fontSize = h-4;
  166. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  167. g2.setFont(font);
  168. char[] chars = code.toCharArray();
  169. for(int i = 0; i < verifySize; i++){
  170. AffineTransform affine = new AffineTransform();
  171. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
  172. g2.setTransform(affine);
  173. g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
  174. }
  175.  
  176. g2.dispose();
  177. ImageIO.write(image, "jpg", os);
  178. }
  179.  
  180. private static Color getRandColor(int fc, int bc) {
  181. if (fc > 255)
  182. fc = 255;
  183. if (bc > 255)
  184. bc = 255;
  185. int r = fc + random.nextInt(bc - fc);
  186. int g = fc + random.nextInt(bc - fc);
  187. int b = fc + random.nextInt(bc - fc);
  188. return new Color(r, g, b);
  189. }
  190.  
  191. private static int getRandomIntColor() {
  192. int[] rgb = getRandomRgb();
  193. int color = 0;
  194. for (int c : rgb) {
  195. color = color << 8;
  196. color = color | c;
  197. }
  198. return color;
  199. }
  200.  
  201. private static int[] getRandomRgb() {
  202. int[] rgb = new int[3];
  203. for (int i = 0; i < 3; i++) {
  204. rgb[i] = random.nextInt(255);
  205. }
  206. return rgb;
  207. }
  208.  
  209. private static void shear(Graphics g, int w1, int h1, Color color) {
  210. shearX(g, w1, h1, color);
  211. shearY(g, w1, h1, color);
  212. }
  213.  
  214. private static void shearX(Graphics g, int w1, int h1, Color color) {
  215.  
  216. int period = random.nextInt(2);
  217.  
  218. boolean borderGap = true;
  219. int frames = 1;
  220. int phase = random.nextInt(2);
  221.  
  222. for (int i = 0; i < h1; i++) {
  223. double d = (double) (period >> 1)
  224. * Math.sin((double) i / (double) period
  225. + (6.2831853071795862D * (double) phase)
  226. / (double) frames);
  227. g.copyArea(0, i, w1, 1, (int) d, 0);
  228. if (borderGap) {
  229. g.setColor(color);
  230. g.drawLine((int) d, i, 0, i);
  231. g.drawLine((int) d + w1, i, w1, i);
  232. }
  233. }
  234.  
  235. }
  236.  
  237. private static void shearY(Graphics g, int w1, int h1, Color color) {
  238.  
  239. int period = random.nextInt(40) + 10; // 50;
  240.  
  241. boolean borderGap = true;
  242. int frames = 20;
  243. int phase = 7;
  244. for (int i = 0; i < w1; i++) {
  245. double d = (double) (period >> 1)
  246. * Math.sin((double) i / (double) period
  247. + (6.2831853071795862D * (double) phase)
  248. / (double) frames);
  249. g.copyArea(i, 0, 1, h1, 0, (int) d);
  250. if (borderGap) {
  251. g.setColor(color);
  252. g.drawLine(i, (int) d, i, 0);
  253. g.drawLine(i, (int) d + h1, i, h1);
  254. }
  255.  
  256. }
  257.  
  258. }
  259. public static void main(String[] args) throws IOException{
  260. File dir = new File("F:/verifies");
  261. int w = 200, h = 80;
  262. for(int i = 0; i < 50; i++){
  263. String verifyCode = generateVerifyCode(4);
  264. File file = new File(dir, verifyCode + ".jpg");
  265. outputImage(w, h, file, verifyCode);
  266. }
  267. }
  268. }

2:controller中调用工具类,生成图片:

  1. @RequestMapping("/getValidateImg")
  2. public void getValidateImg(HttpServletRequest request, HttpServletResponse response) throws IOException{
  3. //设置响应格式
  4. response.setContentType("image/jpeg");
  5. //禁止图像缓存
  6. response.setHeader("Pragma", "No-cache");
  7. response.setHeader("Cache-Control", "no-cache");
  8. response.setDateHeader("Expires", 0);
  9. response.setContentType("image/jpeg");
  10.  
  11. //生成随机字串(4:验证码的尺寸)
  12. String verifyCode = ValidateUtil.generateVerifyCode(4);
  13. //存入会话session
  14. HttpSession session = request.getSession(true);
  15. //删除以前的
  16. session.removeAttribute("verCode");
  17. session.setAttribute("verCode", verifyCode.toLowerCase());
  18. //生成图片
  19. int w = 80, h = 40;
  20. ValidateUtil.outputImage(w, h, response.getOutputStream(), verifyCode);
  21. }

3:jsp页面的写法,可更换验证码图片:

  1. <!-- 验证码 -->
  2. <tr>
  3. <td nowrap width="437"></td>
  4. <td>
  5. <img id="img" src="${ctx}/authImage" />
  6. <a href='#' onclick="javascript:changeImg()" style="color:white;"><label style="color:white;">看不清?</label></a>
  7. </td>
  8. </tr>
  9.  
  10. <!-- 触发JS刷新-->
  11. <script type="text/javascript">
  12. function changeImg(){
  13. var img = document.getElementById("img");
  14. img.src = "${ctx}/authImage?date=" + new Date();;
  15. }
  16. </script>

java中生成验证码,以及验证码的使用的更多相关文章

  1. JAVA中生成指定位数随机数的方法总结

    JAVA中生成指定位数随机数的方法很多,下面列举几种比较常用的方法. 方法一.通过Math类 public static String getRandom1(int len) { int rs = ( ...

  2. 关于android开发添加菜单XML文件之后无法在R.java中生成ID的问题

    因为和同学分开做的android软件,现在想整合他做的界面部分,于是拷贝了res和src文件夹的文件,其中包括一个res.menu文件夹中的XML.但是每次将该文件导入到工程总无法自动在R.java中 ...

  3. 在java中生成二维码,并直接输出到jsp页面

    在java中生成的二维码不存到磁盘里要直接输出到页面上,这就需要把生成的二维码直接以流的形式输出到页面上,我用的是myeclipse 和 tomcat 它的原理是:在加载页面时,根据img的src(c ...

  4. JAVA中生成、解析二维码图片的方法

    JAVA中生成.解析二维码的方法并不复杂,使用google的zxing包就可以实现.下面的方法包含了生成二维码.在中间附加logo.添加文字功能,并有解析二维码的方法. 一.下载zxing的架包,并导 ...

  5. 【学习笔记】Java中生成对象的5中方法

    概述:本文介绍以下java五种创建对象的方式: 1.用new语句创建对象,这是最常用的创建对象的方式. 2.使用Class类的newInstance方法 3.运用反射手段,调用java.lang.re ...

  6. Java中生成帮助文档

    如何在Java中使用注释 在编写程序时,经常需要添加一些注释,用以描述某段代码的作用. 一般来说,对于一份规范的程序源代码而言,注释应该占到源代码的 1/3 以上.因此,注释是程序源代码的重要组成部分 ...

  7. java中生成不重复随机的数字

    Java中产生随机数 1 . 调用java.lang下面Math类中的random()方法产生随机数 新建一个文件后缀名为java的文件,文件名取为MyRandom,该类中编写如下的代码: publi ...

  8. java中生成和验证jwt

    在这篇文章中主要记录一下在Java中如何使用 java 代码生成jwt token,主要是使用jjwt来生成和验证jwt,关于什么是JWT,以及JWT可以干什么不做详解. jwt的格式: base64 ...

  9. Java随机生成常用汉字验证码

    原文:http://www.open-open.com/code/view/1422514803970 import java.awt.Color; import java.awt.Font; imp ...

随机推荐

  1. 转《Angular4项目部署到服务器上刷新404解决办法》

    刚遇到Angular4项目npm run build 后部署到服务器可以访问,但是刷新页面会出现404的错误!转载一大神的操作 解决angular2页面刷新后报404错误办法: 配置app.modul ...

  2. 捕捉JDialog的关闭事件

    捕捉JDialog的关闭事件 http://xxqn.iteye.com/blog/431190 public class EditJDialog extends javax.swing.JDialo ...

  3. 聊聊我怎么系统学习Linux技能并快速提高的

    随着电子信息科技时代的发展,学会使用计算机在我们的生活中成为了必不可少的一项技能.而作为计算机中的三大操作系统之一的Linux更是饱受计算机爱好者们的喜爱.今天我们就来和大家一起聊一聊Linux操作系 ...

  4. BZOJ2214[Poi2011]Shift——模拟

    题目描述 Byteasar bought his son Bytie a set of blocks numbered from to and arranged them in a row in a ...

  5. es6箭头函数内部判断

    ES6闭包内部判断 需要判断i值和数组长度的关系,一旦大于i归0 未加入判断 setInterval((i => (() =>( this.$refs.danmu.render(ret.d ...

  6. 洛谷P3345 [ZJOI2015]幻想乡战略游戏(动态点分治,树的重心,二分查找,Tarjan-LCA,树上差分)

    洛谷题目传送门 动态点分治小白,光是因为思路不清晰就耗费了不知道多少时间去gang这题,所以还是来理理思路吧. 一个树\(T\)里面\(\sum\limits_{v\in T} D_vdist(u,v ...

  7. 架构师成长之路4.4-多维监控体系_zabbix

    点击返回架构师成长之路 点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 架构师成长之路4.4-多维监控体系_zabbix 自学Zabbix之路[第 ...

  8. 架构师成长之路2.2-PXE+Kickstart安装部署

    点击返回架构师成长之路 架构师成长之路2.2-PXE+Kickstart安装部署 系统测试环境: 实验环境:VMware Workstation 12 系统平台:CentOS Linux releas ...

  9. Java 关键字final的一小结

     * final类不能被继承,没有子类,final类中的方法默认是final的.  * final方法不能被子类的方法覆盖,但可以别继承  (方法)  * final 成员变量 表示常量,只能被赋值一 ...

  10. elasticsearch 安装、配置

    elasticsearch:基于java开发,基于RESTful web 接口,提供分布式多用户能力的全文搜索引擎. elasticsearch 安装: 1. java SE Development ...