package com.example.demo.module.captcha;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * 控制器-验证码
 */
@CrossOrigin
@Controller
@RequestMapping("/api")
public class CaptchaController {
    /**
     * 用于生成带四位数字验证码的图片
     */
    @RequestMapping(value = "/createCaptcha")
    @ResponseBody
    public String createCaptchaImageCode(HttpServletRequest request, HttpServletResponse response, String code) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();
        Map<String,Object> map = CaptchaImage.getImageCode(code,86, 37, os);
        try {
            ImageIO.write((BufferedImage) map.get("image"), "jpg", os);
        } catch (IOException e) {
            return "";
        }  finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        return null;
    }
}