package cn.pluss.platform.controller.home;

import cn.pluss.platform.constants.Constant;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 *
 *获取图形验证码
 *@author: bzg
 *@time: 2021/12/20 11:30
 */
@RestController
@RequestMapping(value = "kaptcha")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/get")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应头
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String text = defaultKaptcha.createText();
        HttpSession session = request.getSession();
        //将验证码存入session
        session.setAttribute(Constant.LOGIN_VALIDATE_CODE, text);
        //创建验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(image, "jpg", os);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(image, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
