In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "java how to achieve random CAPTCHA picture generation". In daily operation, I believe many people have doubts about how to achieve random CAPTCHA picture generation in java. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "how to achieve random CAPTCHA picture generation in java". Next, please follow the editor to study!
The details are as follows
1.controller
/ * get random number verification code picture * * @ param request HttpServletRequest * @ param response HttpServletResponse * / @ GetMapping (value = "/ getRandomCode", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public void getRandomCode (HttpServletRequest request, HttpServletResponse response) {baseService.getRandomCode (request, response);}
2.service
Void getRandomCode (HttpServletRequest request, HttpServletResponse response)
3.serviceImpl
@ Autowired private RedisTemplate redisTemplate; @ Autowired private CodeImageUtils codeImageUtils; / * get random number verification code picture * / @ Override public void getRandomCode (HttpServletRequest request, HttpServletResponse response) {try {/ / set the output type to picture response.setContentType ("image/jpeg"); / / generate random code String verificationCode = codeImageUtils.getRandomCode () / / background color and character color Color color = codeImageUtils.getRandomColor (); Color reverseColor = codeImageUtils.getReverseColor (color); / / create a color picture BufferedImage bi = new BufferedImage (100,30, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = bi.createGraphics () / / set font graphics.setFont (new Font (Font.SANS_SERIF, Font.BOLD, 16); graphics.setColor (color); / / draw background graphics.fillRect (0,0,100,30); graphics.setColor (reverseColor); / / draw character graphics.drawString (verificationCode, 18,20) / / draw up to 50 random noise points / / draw up to 50 random noise points Random random = new Random (); int n = random.nextInt (50); for (int I = 0; I
< n; i++) { graphics.drawRect(100, 30, 1, 1); } // 放到redis中 sessionId:code,过期时间60s redisTemplate.opsForValue().set(request.getSession().getId(),verificationCode,60, TimeUnit.SECONDS); //输出到客户端 ServletOutputStream sos = response.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos); encoder.encode(bi); sos.flush(); }catch (Exception ex){ log.error("生成验证码失败!",ex); } } 4.CodeImageUtils @Componentpublic class CodeImageUtils { @Autowired RedisTemplate redisTemplate; /** * 生成4位随机的验证码字符串 * * @return */ public String getRandomCode() { // 通过random生成4位随机数字码 Random random = new Random(); StringBuilder rs = new StringBuilder(); for (int i = 0; i < 4; i++) { rs.append(random.nextInt(10)); } return rs.toString(); } /** * 生成随机的颜色 * * @return */ public Color getRandomColor() { Random random = new Random(); return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } /** * 获取某颜色的反色 * @param color * @return */ public Color getReverseColor(Color color) { return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue()); } /** * 校验 * @param code * @return */ public boolean valid(HttpServletRequest request,String code){ // 获取缓存的code Object cacheCode = redisTemplate.opsForValue().get(request.getSession().getId()); if(cacheCode ==null){ return false; } return code.equals(cacheCode); }} 5.请求该接口6.ImageIO
JPEGCodec expired in the higher version of jdk and was replaced by ImageIO
/ / output to client ServletOutputStream sos = response.getOutputStream (); / * JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (sos); encoder.encode (bi); * / ImageIO.write (bi, "PNG", sos); sos.flush ()
7.sessionId inconsistency
The above code does not find any problems for the time being in the case of single-node deployment, but there will be sessionId inconsistencies in multi-node deployment. (don't ask me how I know. Stepping on the pit makes me progress.
The solution is to use the @ EnableRedisHttpSession annotation to turn on session sharing.
New dependence
Org.springframework.session spring-session-data-redis 2.1.12.RELEASE
New configuration
@ EnableRedisHttpSession (maxInactiveIntervalInSeconds = 86400) at this point, the study on "how to achieve random CAPTCHA image generation by java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.