xiaoyong931011
2022-06-15 6c82b0f944a0d3547659db5ec1f640a9ec7d3fd3
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
package com.xcong.farmer.cms.modules.system.util;
 
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xcong.farmer.cms.common.response.Result;
import com.xcong.farmer.cms.modules.system.service.ICommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
 
@Component
public class CaptchaUtil {
 
    @Autowired
    private DefaultKaptcha producer;
    @Autowired
    private ICommonService iCommonService;
    //生成catchCreator的map
    public Result catchaImgCreator() throws IOException {
        //生成文字验证码
        String text = producer.createText();
        //生成文字对应的图片验证码
        BufferedImage image = producer.createImage(text);
        //将图片写出
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        //对写出的字节数组进行Base64编码 ==> 用于传递8比特字节码
        BASE64Encoder encoder = new BASE64Encoder();
        //生成token
        Map<String, Object> token = iCommonService.createToken(text);
        token.put("img", encoder.encode(outputStream.toByteArray()));
        return Result.ok(token);
    }
}