1:工具类
@Slf4j
public class RandomValidateCode {private static String baseNumLetter = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";private static String font = "微软雅黑";//绘制验证码图片,返回验证码文本内容public static String drawRandomText(int width, int height, BufferedImage verifyImg) {Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();graphics.setColor(Color.WHITE);//设置画笔颜色-验证码背景色graphics.fillRect(0, 0, width, height);//填充背景graphics.setFont(new Font(font, Font.BOLD, 30));StringBuffer sBuffer = new StringBuffer();int x = 10; //旋转原点的 x 坐标String ch = "";Random random = new Random();for (int i = 0; i < 4; i++) {graphics.setColor(getRandomColor());//设置字体旋转角度int degree = random.nextInt() % 30; //角度小于30度int dot = random.nextInt(baseNumLetter.length());ch = baseNumLetter.charAt(dot) +"";sBuffer.append(ch);//正向旋转graphics.rotate(degree * Math.PI / 180, x, 45);graphics.drawString(ch, x, 45);//反向旋转graphics.rotate(-degree * Math.PI / 180, x, 45);x += 48;}//画干扰线/*for (int i = 0; i < 30; i++) {// 设置随机颜色graphics.setColor(getRandomColor());// 随机画线graphics.drawLine(random.nextInt(width), random.nextInt(height),random.nextInt(width), random.nextInt(height));}//添加噪点for (int i = 0; i < 200; i++) {int x1 = random.nextInt(width);int y1 = random.nextInt(height);graphics.setColor(getRandomColor());graphics.fillRect(x1, y1, 2, 2);}*/log.info("======图文验证:{}", sBuffer.toString());return sBuffer.toString();}//获取随机颜色private static Color getRandomColor() {Random ran = new Random();Color color = new Color(ran.nextInt(256),ran.nextInt(256), ran.nextInt(256));return color;}
2:方法层
String getCheckCode(String phone, BufferedImage verifyImg);
3:业务层
@Override
public String getCheckCode(String phone, BufferedImage verifyImg) {String randomText = RandomValidateCode.drawRandomText(BaseUtils.TWO_HUNDRED, BaseUtils.SIXTY, verifyImg);log.info("RandomValidateCode randomText:{} ", randomText);this.stringRedisTemplateOne.opsForValue().set(BaseUtils.KEY_IMAGE + phone, randomText, BaseUtils.CODE_TIME, BaseUtils.TIME_UNIT);return randomText;
}
4:控制层
@PostMapping("/getCheckCode")
public void getCheckCode(HttpServletResponse response, HttpServletRequest request, @RequestParam(value = "phone") String phone) {try {BufferedImage verifyImg = new BufferedImage(BaseUtils.TWO_HUNDRED, BaseUtils.SIXTY, BufferedImage.TYPE_INT_RGB);request.getSession().setAttribute("verifyCode", userService.getCheckCode(phone, verifyImg));response.setContentType("image/png");//必须设置响应内容类型为图片,否则前台不识别OutputStream os = response.getOutputStream(); //获取文件输出流ImageIO.write(verifyImg, "png", os);//输出图片流os.flush();os.close();//关闭流} catch (IOException e) {}
}
5:页面效果