Java生成图片验证码

素颜马尾好姑娘i 2022-06-07 08:39 388阅读 0赞

功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。

VerifyCodeUtils类,生成图片流,然后不同框架下的输出可以参考上面的代码或者自行百度,无非就是获取outputStream和ContentType的区别,main方法可直接执行:

这里写图片描述

  1. package edu.xt.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. /** * * <p>Title:VerifyCodeUtils </p> * <p>Description: 生成图片流核心代码块</p> * <p>Company: </p> * @author 小桃小涛 * @date 2017年10月15日下午2:45:57 */
  17. public class VerifyCodeUtils {
  18. //去掉了1,0,i,o几个容易混淆的字符
  19. public static final String VERIFYCODES="23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  20. private static Random random = new Random();
  21. /** * @使用系统默认字符源生成验证码 * @param verifySize 验证码长度 * @return */
  22. public static String generateVerifyCode(int verifySize){
  23. return generateVerifyCode(verifySize,VERIFYCODES);
  24. }
  25. /** * @使用指定源生成验证码 * @param verifySize 验证码长度 * @param sources 验证码字符源 * @return */
  26. public static String generateVerifyCode(int verifySize,String sources){
  27. //判断是否有字符源
  28. if(sources==null||sources.length()==0){
  29. sources=VERIFYCODES;
  30. }
  31. int CodeLen = sources.length();
  32. Random random = new Random(System.currentTimeMillis());
  33. StringBuilder verifyCode = new StringBuilder(verifySize);
  34. for(int i=0;i<verifySize;i++){
  35. verifyCode.append(sources.charAt(random.nextInt(CodeLen-1)));
  36. }
  37. return verifyCode.toString();
  38. }
  39. /** * @生成随机验证码文件 并返回验证码值 * @param width * @param height * @param outputFile * @param verifySize * @return * @throws IOException */
  40. public static String outputVerifyImage(int width,int height,File outputFile,int verifySize) throws IOException{
  41. String verifyCode = generateVerifyCode(verifySize);
  42. outputImage(width, height, outputFile, verifyCode);
  43. return verifyCode;
  44. }
  45. public static void outputImage(int width,int height,File outputFile, String code) throws IOException{
  46. if(outputFile==null){
  47. return;
  48. }
  49. File dir = outputFile.getParentFile();
  50. if(!dir.exists()){
  51. dir.mkdirs();
  52. }
  53. try{
  54. outputFile.createNewFile();
  55. FileOutputStream fos = new FileOutputStream(outputFile);
  56. outputImage(width, height, fos, code);
  57. fos.close();
  58. }catch(IOException e){
  59. throw e;//手动抛出IOException 异常
  60. }
  61. }
  62. public static void outputImage(int width,int height,OutputStream os,String code) throws IOException{
  63. int verifySize = code.length();
  64. //创建一个画板
  65. BufferedImage buf =new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  66. Random random = new Random();
  67. //创建一个绘图工具
  68. Graphics2D gs= buf.createGraphics();
  69. //消除线段的锯齿状边缘
  70. gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  71. //创建颜色集合
  72. Color[] colors = new Color[5];
  73. Color[] colorSpaces = new Color[]{
  74. Color.WHITE, Color.CYAN,
  75. Color.GRAY, Color.LIGHT_GRAY,
  76. Color.MAGENTA, Color.ORANGE,
  77. Color.PINK, Color.YELLOW
  78. };
  79. Float[] fractions = new Float[colors.length];
  80. for(int i=0;i<colors.length;i++){
  81. colors[i]=colorSpaces[random.nextInt(colorSpaces.length)];
  82. fractions[i]=random.nextFloat();
  83. }
  84. Arrays.sort(fractions);//排序
  85. //设置边框色
  86. gs.setColor(Color.GRAY);
  87. gs.fillRect(0, 0, width, height);
  88. Color c= getRandomColor(200, 500);
  89. gs.setColor(c);
  90. gs.fillRect(0, 2, width, height-4);
  91. //绘制干扰线
  92. Random rand = new Random();
  93. gs.setColor(getRandomColor(160, 200));
  94. for(int i=0;i<20;i++){
  95. int x=rand.nextInt(width-1);
  96. int y= rand.nextInt(height-1);
  97. int x1=rand.nextInt(6)+1;
  98. int y1 = rand.nextInt(12)+1;
  99. gs.drawLine(x, y, x+x1+40, y+y1+20);
  100. }
  101. //添加噪点
  102. float yawpRate =0.05f;//噪点率
  103. int area = (int)(yawpRate*width*height);
  104. for(int i=0;i<area;i++){
  105. int x=random.nextInt(width);
  106. int y=random.nextInt(height);
  107. int rgb = getRandomIntColor();
  108. buf.setRGB(x, y, rgb);
  109. }
  110. //使图片扭曲
  111. shear(gs,width,height,c);
  112. gs.setColor(getRandomColor(100, 160));
  113. int fontSize=height-4;
  114. Font font = new Font("Algerian",Font.ITALIC,fontSize);
  115. gs.setFont(font);
  116. char[] chars = code.toCharArray();
  117. for(int i=0;i<verifySize;i++){
  118. AffineTransform affine = new AffineTransform();
  119. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (width/ verifySize) * i + fontSize/2, height/2);
  120. gs.setTransform(affine);
  121. gs.drawChars(chars, i, 1, ((width-10) / verifySize) * i + 5, height/2 + fontSize/2 - 10);
  122. }
  123. gs.dispose();
  124. ImageIO.write(buf, "JPEG", os);
  125. }
  126. /** * @rgb颜色的区域是0~255 * @param fc * @param bc * @return */
  127. private static Color getRandomColor(int fc,int bc){
  128. if(fc>255) fc=255;
  129. if(bc>255) bc=255;
  130. int r=fc+random.nextInt(bc-fc);
  131. int g=fc+random.nextInt(bc-fc);
  132. int b=fc+random.nextInt(bc-fc);
  133. return new Color(r,g,b);
  134. }
  135. private static int getRandomIntColor(){
  136. int[] rgb = getRandomRgb();
  137. int color=0;
  138. for (int c : rgb) {
  139. color=color<<8;
  140. color=color|c;
  141. }
  142. return color;
  143. }
  144. private static int[] getRandomRgb(){
  145. int[] rgb = new int[3];
  146. for(int i=0;i<3;i++){
  147. rgb[i]=random.nextInt(255);
  148. }
  149. return rgb;
  150. }
  151. private static void shear(Graphics g,int w ,int h,Color color){
  152. shearX(g,w,h,color);
  153. shearY(g,w,h,color);
  154. }
  155. private static void shearX(Graphics g,int w ,int h,Color color){
  156. int period = random.nextInt(2);
  157. boolean borderGap =true;
  158. int frames =1;
  159. int phase = random.nextInt(2);
  160. for(int i=0;i<h;i++){
  161. //???????
  162. double d = (double) (period >> 1)
  163. * Math.sin((double) i / (double) period
  164. + (6.2831853071795862D * (double) phase)
  165. / (double) frames);
  166. g.copyArea(0, i, w, 1, (int) d, 0);
  167. if(borderGap){
  168. g.setColor(color);
  169. g.drawLine((int)d, i, 0, i);
  170. g.drawLine((int)d+w, i, w, i);
  171. }
  172. }
  173. }
  174. private static void shearY(Graphics g, int w, int h, Color color) {
  175. int period = random.nextInt(40) + 10; // 50;
  176. boolean borderGap = true;
  177. int frames = 20;
  178. int phase = 7;
  179. for (int i = 0; i < w; i++) {
  180. double d = (double) (period >> 1)
  181. * Math.sin((double) i / (double) period
  182. + (6.2831853071795862D * (double) phase)
  183. / (double) frames);
  184. g.copyArea(i, 0, 1, h, 0, (int) d);
  185. if (borderGap) {
  186. g.setColor(color);
  187. g.drawLine(i, (int) d, i, 0);
  188. g.drawLine(i, (int) d + h, i, h);
  189. }
  190. }
  191. }
  192. public static void main(String[] args){
  193. File dir = new File("D:/学习文档/验证码/verify");
  194. int width=200,height=80;
  195. String verifyCode = generateVerifyCode(4);
  196. File file = new File(dir,verifyCode+".jpg");
  197. try {
  198. outputImage(width, height, file, verifyCode);
  199. } catch (IOException e) {
  200. e.printStackTrace();
  201. }
  202. }
  203. }

AuthImage类

  1. package edu.xt.utils;
  2. import java.io.IOException;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import javax.servlet.http.HttpSession;
  6. public class AuthImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet{
  7. private static final long serialVersionUID = 1L;
  8. public void service(HttpServletRequest request, HttpServletResponse response) throws IOException{
  9. response.setHeader("Pragma", "No-cache");
  10. response.setHeader("Cache-Control", "no-cache");
  11. response.setDateHeader("Expires", 0);
  12. response.setContentType("image/jpeg");
  13. //生成随机字符串
  14. String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
  15. //存入会话 session
  16. HttpSession session = request.getSession(true);
  17. //删除以前的
  18. session.removeAttribute("rand");
  19. session.setAttribute("rand", verifyCode.toString());
  20. //生成图片
  21. int w=200,h=60;
  22. VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
  23. }
  24. }

xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  3. <display-name>VerifyCode</display-name>
  4. <servlet>
  5. <servlet-name>AuthImage</servlet-name>
  6. <servlet-class>edu.xt.utils.AuthImage</servlet-class>
  7. </servlet>
  8. <servlet-mapping>
  9. <servlet-name>AuthImage</servlet-name>
  10. <url-pattern>/authImage</url-pattern>
  11. </servlet-mapping>
  12. <welcome-file-list>
  13. <welcome-file>index.html</welcome-file>
  14. <welcome-file>index.htm</welcome-file>
  15. <welcome-file>index.jsp</welcome-file>
  16. <welcome-file>default.html</welcome-file>
  17. <welcome-file>default.htm</welcome-file>
  18. <welcome-file>default.jsp</welcome-file>
  19. </welcome-file-list>
  20. </web-app>

最后界面效果
这里写图片描述

  1. <%@ page language="java" pageEncoding="UTF-8"%>
  2. <!doctype html>
  3. <html>
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="Keywords" content="关键字、关键词">
  7. <meta name="Description" content="描述语句">
  8. <title>VerifyCode验证码</title>
  9. </head>
  10. <body>
  11. <table>
  12. <tr>
  13. <td nowrap width="437"></td>
  14. <td>
  15. <img id="img" src="authImage" />
  16. <a href='#' onclick="javascript:changeImage()"><label>看不清?</label></a>
  17. </td>
  18. </tr>
  19. </table>
  20. <script type="text/javascript" src="js/jquery-3.1.0.js"></script>
  21. <script type="text/javascript"> function changeImage(){ var img = document.getElementById("img"); img.src = "authImage?date=" + new Date(); } </script>
  22. </body>
  23. </html>

发表评论

表情:
评论列表 (有 0 条评论,388人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java生成图片验证

    功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。 VerifyCodeUtils类,生成图片流,然后不同框

    相关 生成图片验证

    问题描述 在项目中遇到有人恶意拉取图片资源,无限刷资源,导致阿里图片服务器流量暴涨(钱遭不住),使得带宽一直处于上限,正常用户不能好的访问。 解决办法 这个功能设