1 package com.donleo.ssm.common; 2 3 4 import com.donleo.ssm.utils.CommonPath; 5 import redis.clients.jedis.Jedis; 6 7 import javax.imageio.ImageIO; 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import java.awt.*; 14 import java.awt.image.BufferedImage; 15 import java.io.IOException; 16 import java.io.OutputStream; 17 import java.util.Random; 18 19 /** 20 * @author liangd 21 * date 2020-10-16 11:31 22 * code 生成验证码图片 23 */ 24 @WebServlet("/code") 25 public class CodeServlet extends HttpServlet { 26 @Override 27 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 28 //创建空白图片 29 BufferedImage image = new BufferedImage(90, 30, BufferedImage.TYPE_INT_RGB); 30 //1.获取图片画笔 31 Graphics g = image.getGraphics(); 32 Random r = new Random();//随机数 33 // r.nextInt(255),随机数在0到255之间 而且必须是整数 34 //2.设置画笔颜色 35 // 设置背景颜色,RGB 三个参数 36 g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255))); 37 //3. .绘制矩形的背景 38 g.fillRect(0, 0, 90, 30); 39 40 41 //4.调用自定义的方法,获取长度为5的字母数字组合的字符串 42 String number = getNumber(5); 43 // System.out.println(number); 44 req.getSession().setAttribute("code", number); 45 Jedis jedis = new Jedis(); 46 jedis.auth(CommonPath.REDIS_AUTH.getValue()); 47 jedis.set("backCode",number); 48 g.setColor(new Color(0, 0, 0)); 49 g.setFont(new Font("宋体", Font.BOLD, 24)); 50 //5.设置颜色字体后,绘制字符串 51 g.drawString(number, 5, 25); 52 //6.绘制8条干扰线 53 for (int i = 0; i < 18; i++) { 54 g.setColor(new 55 Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255))); 56 g.drawLine(r.nextInt(90), 57 r.nextInt(30), 58 r.nextInt(90), 59 r.nextInt(30)); 60 // 直线参数 (a,b,x,y),a,b代表起点,x,y代表终点 61 } 62 resp.setContentType("image/ jpeg"); 63 OutputStream ops = resp.getOutputStream(); 64 ImageIO.write(image, "jpeg", ops); 65 ops.close(); 66 67 } 68 69 /** 70 * 字符串的拼接 71 * 72 * @param size 73 * @return 74 */ 75 private String getNumber(int size) { 76 //把I和O都去掉,因为和1,0不好识别 77 String str = "ASDFGHJKLQWERTYUIOPZXCVBNM"; 78 StringBuilder number = new StringBuilder(); 79 Random r = new Random(); 80 for (int i = 0; i < size; i++) { 81 number.append(str.charAt(r.nextInt(str.length()))); 82 // str.charAt 拿到下标为0-str长度之间的下标,下标从0开始 83 } 84 return number.toString(); 85 } 86 }