http://blog.csdn.net/ruixue0117/article/details/22829557

java:

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

这里在方法后面加个随机数是为了请求路径发生变化而进行请求,js:

  1. function loadimage(){
  2. $("#randImage").attr("src", "VerifyCodeServlet?"+Math.random());
  3. }

html:

  1. <form id="log-and-reg" class="form-horizontal">
  2. <h3>登录</h3>
  3. <div class="form-group">
  4. <div class="col-sm-12">
  5. <input type="email" class="form-control" id="username" placeholder="邮箱">
  6. </div>
  7. </div>
  8. <div class="form-group">
  9. <div class="col-sm-12">
  10. <input type="password" class="form-control" id="password" placeholder="密码">
  11. </div>
  12. </div>
  13. <div class="form-group">
  14. <div class="col-sm-6">
  15. <input type="text" class="form-control" id="verificationCode" placeholder="验证码">
  16. </div>
  17. <div class="col-sm-6">
  18. <a class="verification-code pull-right" href="javascript:loadimage()">
  19. <img id="randImage" src="VerifyCodeServlet" />
  20. </a>
  21. </div>
  22. </div>
  23. <div class="form-group">
  24. </div>
  25. <div class="form-group">
  26. <div class="col-sm-6">
  27. <div class="checkbox">
  28. <label class="remember-pass"><input type="checkbox"> 记住密码</label>
  29. </div>
  30. </div>
  31. <div class="col-sm-6">
  32. <a class="forget-pass pull-right" href="${BASE}/forgetpsw">忘记密码</a>
  33. </div>
  34. </div>
  35.  
  36. <div class="form-group">
  37. <div class="col-sm-12">
  38. <button type="button" class="btn-submit" onclick="login()">登录</button>
  39. </div>
  40. <div class="col-sm-12">
  41. <p class="immediately-switch">还没有帐号?<a href="#" data-toggle="modal" data-target="#myModal">马上注册</a></p>
  42. </div>
  43. </div>
  44. </form>

转:Java生成图片验证码(有点仿QQ验证码的意思)的更多相关文章

  1. 网上的仿QQ验证码,详细使用方法

    struts2的配置 和代码 1.生成图片流 类名:VerifyCodeUtils /** * 生成图片流 * @author Administrator * */ import java.awt.C ...

  2. 【转】Java生成图片验证码

    原文转自:http://blog.csdn.net/ruixue0117/article/details/22829557 看了挺多图片验证码的代码,感觉没什么长的好看点的,就自己动手写了个,写完发现 ...

  3. < JAVA - 大作业(2)仿qq即时通讯软件 >

    < JAVA - 大作业(2)仿qq即时通讯软件 > 背景 JAVA上机大作业:设计一个仿qq即时通讯软件 任务简要叙述:设计一款仿QQ的个人用户即时通讯软件,能够实现注册,登陆,与好友聊 ...

  4. Java中SSM+Shiro系统登录验证码的实现方法

    1.验证码生成类: import java.util.Random; import java.awt.image.BufferedImage; import java.awt.Graphics; im ...

  5. java实现注册的短信验证码

    最近在做只能净化器的后台用户管理系统,需要使用手机号进行注册,找了许久才大致了解了手机验证码实现流程,今天在此和大家分享一下. 我们使用的是榛子云短信平台, 官网地址:http://smsow.zhe ...

  6. Java 实现手机发送短信验证码

    Java 实现手机发送短信验证码 采用引入第三方工具的方式,网上查了半天,发现简单的实现方式便是注册一个中国网建的账号,新建账号的时候会附带赠几条免费短信,彩信 ,之后想要在使用就得花钱了.简单的操作 ...

  7. 仿QQ聊天程序(java)

    仿QQ聊天程序 转载:牟尼的专栏 http://blog.csdn.net/u012027907 一.设计内容及要求 1.1综述 A.系统概述 我们要做的就是类似QQ这样的面向企业内部的聊天软件,基本 ...

  8. 编写Java程序,使用Swing布局管理器和常用控件,实现仿QQ登录界面

    返回本章节 返回作业目录 需求说明: 使用Swing布局管理器和常用控件,实现仿QQ登录界面 实现思路: 创建登录界面的类QQLogin,该类继承父类JFrame,在该类中创建无参数的构造方法,在构造 ...

  9. C# 实现简单仿QQ登陆注册功能

    闲来没事,想做一个仿QQ登陆注册的winform,于是利用工作之余,根据自己的掌握和查阅的资料,历时4天修改完成,新手水平,希望和大家共同学习进步,有不同见解希望提出! 废话不多说,进入正题: 先来看 ...

随机推荐

  1. Oracle Linux 挂载存储

    #启动多路径multipathd服务 service multipathd restart #设置开机自动启动multipathd服务 chkconfig multipathd on #查看信息mul ...

  2. Install the OpenStack command-line

    Install the OpenStack command-line Install the prerequisite software python 2.7 or later note: Curre ...

  3. 异步tcp通信——APM.Core 服务端概述

    为什么使用异步 异步线程是由线程池负责管理,而多线程,我们可以自己控制,当然在多线程中我们也可以使用线程池.就拿网络扒虫而言,如果使用异步模式去实现,它使用线程池进行管理.异步操作执行时,会将操作丢给 ...

  4. nginx配置学习文章

    partOne 自我释义部分 我的是阿里云的ubuntu *******实际上感觉这里是基本配置,很用不到*********#定义其用户或用户组user www-data;#nginx的进程数,应当为 ...

  5. W3C小组宣布:HTML5标准制定完成

    近日,W3C小组宣布已经完成对HTML5标准以及Canvas 2D性能草案的制定,这就意味着开发人员将会有一个稳定的“计划和实施”目标. Web性能工作组已经推出W3C的两个版本建议草案. Navig ...

  6. Android中滑动关闭Activity

    继承SwipeBackActivity即可实现向右滑动删除Activity效果 点击下载所需文件

  7. Qt5遇到的问题

    好久没用Qt了,今天又重新安装了一个,结果遇到不少问题 本机环境:VS2015,Qt5.7 装好后,就新建工程测试了一下,结果无法编译,提示 :-1: error: cannot open C:\Us ...

  8. Intellij idea 12和设置快捷键修改(加快项目的开发速度与养成良好习惯)

    1.为了养成良好的代码习惯idead中的javascript jSLint能显示不良的代码设置如下    2.Intellij idea 12每一次修改,保存生成都要按ctrl+shift+F9非常影 ...

  9. 微信 回复多图文 借助php框架

    private function replyMostPhoto($data,$arr){$this->logger("已经到达回复多图文!".$arr[0]['Title'] ...

  10. 逆天的IE7中,绝对定位元素之间的遮盖问题

    个人比较支持IE9以上的版本,认为他们的样式和效果都是比较人性化的,不过很多时候还是不得不考虑其他版本浏览器的感受,这里IE6就不用考虑他了,这货简直就是IT史上的奇葩,这里要说一个IE7的绝对定位和 ...