这种:

Java  代码、 SpringMVC  方式的Controller代码。

  1. @RequestMapping(value="getYzm",method=RequestMethod.GET)
  2. public void getYzm(HttpServletResponse response,HttpServletRequest request){
  3. try {
  4. response.setHeader("Pragma", "No-cache");
  5. response.setHeader("Cache-Control", "no-cache");
  6. response.setDateHeader("Expires", 0);
  7. response.setContentType("image/jpeg");
  8. //生成随机字串
  9. String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
  10. //存入会话session
  11. HttpSession session = request.getSession(true);
  12. session.setAttribute("_code", verifyCode.toLowerCase());
  13. //生成图片
  14. int w = 146, h = 33;
  15. VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
  16. } catch (Exception e) {
  17. LoggerUtils.fmtError(getClass(),e, "获取验证码异常:%s",e.getMessage());
  18. }
  19. }

下面给出Javascript代码。

  1. <#-- 获取验证码 -->
  2. $("#getYzm").click(function(){
  3. var url = "http://www.sojson.com/getYzm.shtml?t=" + Math.random();
  4. this.src = url;
  5. }).click().show();

这里用到一个工具类。VerifyCodeUtils.java。

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

Java生成验证码合集(一)简单版相关推荐

  1. Java——集合(合集,简单的概括)

    JAVA --集合 集合 概念: 1 .Collection接口与Iterator接口 2 .Collection<>接口 3 . List<>接口 3 .1 ArrayLis ...

  2. 2022年国内最牛的Java面试八股文合集(MCA版),不接受反驳

    纵观今年的技术招聘市场, Java依旧是当仁不让的霸主 !即便遭受 Go等新兴语言不断冲击,依旧岿然不动.究其原因: Java有着极其成熟的生态,这个不用我多说: Java在 运维.可观测性.可监 控 ...

  3. java生成验证码实例_Java生成验证码功能实例代码

    页面上输入验证码是比较常见的一个功能,实现起来也很简单.给大家写一个简单的生成验证码的示例程序,需要的朋友可以借鉴一下. 闲话少续,直接上代码.代码中的注释很详细. package com.SM_te ...

  4. java生成验证码并进行验证

    一实现思路 使用BufferedImage用于在内存中存储生成的验证码图片 使用Graphics来进行验证码图片的绘制,并将绘制在图片上的验证码存放到session中用于后续验证 最后通过ImageI ...

  5. 【毕设|Java项目开发合集】(附源码)

    [毕设|Java项目开发合集] 14个Java项目(附源码)助你轻松搞定毕业设计! 1.新冠疫情统计系统 2.家教系统 3.进销存管理系统 4.饮食分享平台 5.宠物领养平台 6.销售评价系统 7.酒 ...

  6. java生成验证码的三种方法

    java生成验证码的三种方法 第一种:导入jar包com.github.axet生成法 ①导包 <dependency><groupId>com.github.axet< ...

  7. Java面试核心知识点(283页)Java面试题合集最新版(485页)

    阿里.腾讯两大互联网企业传来裁员消息,很多人都陷入担心,不安情绪蔓延-- 其实大家应该更冷静和理性地看待大厂裁员.每年三四月都是大厂人员调整期,这个季节是各个公司战略调整.战略规划的一个关键期,肯定会 ...

  8. 『大牛公司机构近期研究报告大合集』第二版

    免费『大牛公司机构近期研究报告大合集』第二版(阿里.腾讯.麦肯锡.毕马威.德勤.普华永道等几十家倾情巨献!) 2016-03-04 数据局http://mp.weixin.qq.com/s?__biz ...

  9. java入门笔记合集(杂乱)(2)

    java入门笔记合集(杂乱)2 StringBuilder 这是一个容器,可以和String搭配起来用 package day1;import java.util.Scanner;public cla ...

  10. GitChat 最火 Chat 文章合集 | 春节特别版

    要过年了,小编回首往事发现 GitChat 已经上线了 1331 篇 Chat. 这其中有非常多有内涵的文章被大家津津乐道. 这一期,我特意列出了 Chat 从诞生到现在为止最受欢迎的 30 篇文章, ...

最新文章

  1. CTF——angr使用学习记录
  2. 《重新认识你自己》八:与真实的自我相处
  3. Java下载文件的几种方式
  4. Python还值得学吗?
  5. 统计学习方法 第八章总结
  6. mysql高可用性方案(2)
  7. 最新人生感悟语句摘选
  8. CAM表含义及各层交换机介绍
  9. 从细节到宏观的seo方案制定
  10. 1926. Nearest Exit from Entrance in Maze刷题笔记
  11. ABAP基本数据类型
  12. GitHub 热点速览 Vol.24:程序员自我增值,优雅赚零花钱
  13. 选择背光需要对比哪些因素呢?
  14. Windows-空硬盘安装系统
  15. 北京2017年7月开始 社保最低缴费
  16. 基于1939协议的发动机控制程序:包括发动机转速油门控制,发动机常用转速、机油压力、水温、工作小时读取,spn故障码取,发动机启动转速保护
  17. TCP/IP详解之环回接口(loopback interface)
  18. win10,打开软件时总是弹出询问关闭方案
  19. 道闸系统临时服务器什么意思,停车场管理系统常见问题解答
  20. 煮酒论开源语音工具包

热门文章

  1. Linux: 联想小新 Air15 Linux 安装 AX210 网卡驱动
  2. DjVu Reader Pro for Mac(djvu阅读器) v2.2.3激活版
  3. 软件系统设计-13-质量属性
  4. 删除计算机网络无用设备,如何删除我的电脑/计算机中无效的设备和驱动器图标...
  5. 前端开发人员MAC装机工具
  6. Win10下配置IIS并调试ASP程序
  7. 型钢计算机电脑打不开,型钢计算软件
  8. macOS 锐捷校园网解决方案
  9. mysql regexp instr_MySQL 正则表达式:regexp_instr 函数
  10. pscad调用matlab的模块,PSCAD模块库功能教程(包含与matlab接口).pdf