1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| package cn.xmp.generator.demo.user.web;
import cn.apiclub.captcha.Captcha; import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer; import cn.apiclub.captcha.gimpy.FishEyeGimpyRenderer; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.UUID; import java.util.concurrent.TimeUnit;
@Slf4j @RestController @RequestMapping("captcha") public class CaptchaModule {
@Autowired private RedisTemplate<String, String> redisTemplate; @Value("${redis.captchaExpires}") private int captchaExpires; @Value("${redis.captchaW}") private int captchaW; @Value("${redis.captchaH}") private int captchaH;
@RequestMapping(value = "getcaptcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getCaptcha(HttpServletResponse response) { String uuid = UUID.randomUUID().toString(); Captcha captcha = new Captcha.Builder(captchaW, captchaH) .addText().addBackground(new GradiatedBackgroundProducer(Color.red, Color.cyan)) .gimp(new FishEyeGimpyRenderer()) .build();
log.info("验证码答案:{}", captcha.getAnswer()); log.info("验证码配置:{},{},{}", captchaExpires,captchaW,captchaH); redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS); Cookie cookie = new Cookie("CaptchaCode", uuid); response.addCookie(cookie); ByteArrayOutputStream bao = new ByteArrayOutputStream(); try { ImageIO.write(captcha.getImage(), "png", bao); return bao.toByteArray(); } catch (IOException e) { log.info("获取验证码异常:{}", e.getMessage()); return null; } } }
|