1. package com.rchm.util.images;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics2D;
  5. import java.awt.image.BufferedImage;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.OutputStream;
  9. import java.util.Random;
  10. import javax.imageio.ImageIO;
  11. /**
  12. * 验证码生成器
  13. */
  14. public class ValidateCode {
  15. // 图片的宽度。
  16. private int width = 160;
  17. // 图片的高度。
  18. private int height = 40;
  19. // 验证码字符个数
  20. private int codeCount = 5;
  21. // 验证码干扰线数
  22. private int lineCount = 150;
  23. // 验证码
  24. private static String code = null;
  25. // 验证码图片Buffer
  26. private BufferedImage buffImg=null;
  27. private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L',
  28. 'M', 'N',  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y',
  29. 'Z',  '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  30. public  ValidateCode() {
  31. this.createCode();
  32. }
  33. /**
  34. *
  35. * @param width 图片宽
  36. * @param height 图片高
  37. */
  38. public  ValidateCode(int width,int height) {
  39. this.width=width;
  40. this.height=height;
  41. this.createCode();
  42. }
  43. /**
  44. *
  45. * @param width 图片宽
  46. * @param height 图片高
  47. * @param codeCount 字符个数
  48. * @param lineCount 干扰线条数
  49. */
  50. public  ValidateCode(int width,int height,int codeCount,int lineCount) {
  51. this.width=width;
  52. this.height=height;
  53. this.codeCount=codeCount;
  54. this.lineCount=lineCount;
  55. this.createCode();
  56. }
  57. public void createCode() {
  58. int x = 0,fontHeight=0,codeY=0;
  59. int red = 0, green = 0, blue = 0;
  60. x = width / (codeCount +2);//每个字符的宽度
  61. fontHeight = height - 2;//字体的高度
  62. codeY = height - 4;
  63. // 图像buffer
  64. buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
  65. Graphics2D g = buffImg.createGraphics();
  66. // 生成随机数
  67. Random random = new Random();
  68. // 将图像填充为白色
  69. g.setColor(Color.WHITE);
  70. g.fillRect(0, 0, width, height);
  71. // 创建字体
  72. ImgFontByte imgFont=new ImgFontByte();
  73. Font font =imgFont.getFont(fontHeight);
  74. g.setFont(font);
  75. for (int i = 0; i < lineCount; i++) {
  76. int xs = random.nextInt(width);
  77. int ys = random.nextInt(height);
  78. int xe = xs+random.nextInt(width/8);
  79. int ye = ys+random.nextInt(height/8);
  80. red = random.nextInt(255);
  81. green = random.nextInt(255);
  82. blue = random.nextInt(255);
  83. g.setColor(new Color(red, green, blue));
  84. g.drawLine(xs, ys, xe, ye);
  85. }
  86. // randomCode记录随机产生的验证码
  87. StringBuffer randomCode = new StringBuffer();
  88. // 随机产生codeCount个字符的验证码。
  89. for (int i = 0; i < codeCount; i++) {
  90. String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
  91. // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
  92. red = random.nextInt(255);
  93. green = random.nextInt(255);
  94. blue = random.nextInt(255);
  95. g.setColor(new Color(red, green, blue));
  96. g.drawString(strRand, (i + 1) * x, codeY);
  97. // 将产生的四个随机数组合在一起。
  98. randomCode.append(strRand);
  99. }
  100. // 将四位数字的验证码保存到Session中。
  101. code = randomCode.toString();
  102. }
  103. public void write(String path) throws IOException {
  104. OutputStream sos = new FileOutputStream(path);
  105. this.write(sos);
  106. }
  107. public void write(OutputStream sos) throws IOException {
  108. ImageIO.write(buffImg, "png", sos);
  109. sos.close();
  110. }
  111. public BufferedImage getBuffImg() {
  112. return buffImg;
  113. }
  114. public static String getCode() {
  115. return code;
  116. }
  117. }

在 servlet 中使用该类:

  1. package com.rchm.util.images;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import javax.servlet.http.HttpSession;
  8. public class ValidateCodeServlet extends HttpServlet {
  9. private static final long serialVersionUID = 1L;
  10. protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  11. response.setContentType("image/jpeg");
  12. response.setHeader("Pragma", "no-cache");
  13. response.setHeader("Cache-Control", "no-cache");
  14. response.setDateHeader("Expires", 0);
  15. ValidateCode vCode = new ValidateCode(100,30,4,100);
  16. HttpSession session = request.getSession();
  17. session.removeAttribute("validateCode");
  18. vCode.write(response.getOutputStream());
  19. session.setAttribute("validateCode", vCode.getCode());
  20. vCode.write(response.getOutputStream());
  21. }
  22. }

在 web.xml配置Servlet访问路径:

    1. <servlet>
    2. <servlet-name>validateCodeServlet</servlet-name>
    3. <servlet-class>com.rchm.util.images.ValidateCodeServlet</servlet-class>
    4. </servlet>
    5. <servlet-mapping>
    6. <servlet-name>validateCodeServlet</servlet-name>
    7. <url-pattern>code.images</url-pattern>

Java代码随机生成图片验证码的更多相关文章

  1. python 全栈开发,Day85(Git补充,随机生成图片验证码)

    昨日内容回顾 第一部分:django相关 1.django请求生命周期 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这 ...

  2. Django登录(含随机生成图片验证码)注册实例

    登录,生成随机图片验证码 一.登录 - 随机生成图片验证码 1.随机生成验证码 Python随机生成图片验证码,需要使用PIL模块,安装方式如下: pip3 install pillow 1)创建图片 ...

  3. springboot搭建项目,实现Java生成随机图片验证码。

    这篇文章主要介绍了如何通过Java如何生成验证码并验证.验证码的作用我想必大家都知道,话不多说开始实施! 首先创建一个springboot项目以下是项目结构,内有utli工具类.存放生成图片验证码方法 ...

  4. Java生成随机图片验证码

    前台html代码 [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 <div style="margin-top: 50px;&quo ...

  5. Django---登录(含随机生成图片验证码)、注册示例讲解

    登录(验证码).注册功能具体代码 # urls.py from django.contrib import admin from django.urls import path from app01 ...

  6. java代码发送邮箱验证码与qq邮箱smtp服务

    发送邮箱的类封装,在此之前需要一个jar包  javax.mail.jar 下载链接https://github.com/javaee/javamail/releases/download/JAVAM ...

  7. servletResponse 随机生成图片验证码

    /***********************************servlet页面************************************/ package response; ...

  8. java代码--------随机输出100个随机数,要求每行10个数

    总结:不敢爱你么开口 package com.sads; ///实现随机输出100个数字,数字是0到9之间,每行输出10个 public class Wss { public static void ...

  9. python 随机生成图片验证码背景RGB-浅色或者深色

    import random def random_color(is_light = True): return (random.randint(0 ,127) + int(is_light) * 12 ...

随机推荐

  1. Bazinga HDU - 5510 不可做的暴力

    http://acm.hdu.edu.cn/showproblem.php?pid=5510 想了很久队友叫我用ufs + kmp暴力过去了. fa[x] = y表示x是y的子串,所以只有fa[x] ...

  2. Hibernate 批量保存数据

    public Boolean save(Collection<Object> os) { int batchSize = 50,i=0; Session session=this.sess ...

  3. JAVA反射练习

    JAVA反射练习 题目 实现一个方法 public static Object execute(String className, String methodName, Object args[]) ...

  4. 移植mavlink协议到STM32详细教程

    1准备材料, 首先准备一个带串口的stm32程序(这里选用整点原子的官方串口例程这里自己去找不讲)作者:恒久力行 QQ:624668529,然后去mavlink官网下载mavlink源码,这里重点讲解 ...

  5. Django的Serializers的使用

    Serializer 在这里通过一个验证用户身份的例子说明rest_framework中serializer.Serialize的使用. 编写serializer Serializer的使用不需要依赖 ...

  6. img IE下支持最大宽度

    border:0 none; max-width: 560px; height:auto; width:expression(this.width > 600 ? "600px&quo ...

  7. C#高性能Socket服务器IOCP实现

    引言我一直在探寻一个高性能的Socket客户端代码.以前,我使用Socket类写了一些基于传统异步编程模型的代码(BeginSend.BeginReceive,等等)也看过很多博客的知识,在linux ...

  8. Python Visual Studio 2015

    对于一直是C#开发的我来说,上Python是老早就想的事情了. 上次有个项目开始做就说要用Python,后来因为不太熟练就给推掉了.现在终于还是有机会开始下Python之旅. 因为是在Visual S ...

  9. LeetCode Word Ladder 找单词变换梯

    题意:给出两个单词,以及一个set集合,当中是很多的单词.unordered_set是无序的集合,也就是说找的序列也是无序的了,是C++11的标准,可能得升级你的编译器版本了.要求找出一个从start ...

  10. POJ1061 青蛙的约会 __一维世界的爱情

    由于今天上午在做数论知识的笔记,发现那时候赵老师讲的线性丢番图(求ax+by=c的特解)部分完全搞不懂,后来网上查了一下才发现这个公式就是求同余方程,所用方法就是扩展欧几里得算法.正好红皮书上有这么一 ...