1. 程式人生 > 其它 >springboot生成二維碼

springboot生成二維碼

1、引入依賴

		<!--生成二維碼-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.3</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.4.0</version>
        </dependency>

2、編寫service類及方法

@Service
@Slf4j
public class QRCodeService {
    // 自定義引數,這部分是Hutool工具封裝的
    private static QrConfig initQrConfig(int width, int height) {
        QrConfig config = new QrConfig(width, height);
        // 設定邊距,既二維碼和背景之間的邊距
        config.setMargin(3);
        // 設定前景色,既二維碼顏色(青色)
        config.setForeColor(Color.black.getRGB());
        // 設定背景色(灰色)
        config.setBackColor(Color.white.getRGB());
        return config;
    }

    /**
     * 生成到檔案
     *
     * @param content
     * @param filepath
     */
    public void createQRCode2File(String content, int width, int height, String filepath) {
        try {
            QrCodeUtil.generate(content, initQrConfig(width, height), FileUtil.file(filepath));
            log.info("生成二維碼成功, 位置在:{}!", filepath);
        } catch (QrCodeException e) {
            log.error("發生錯誤! {}!", e.getMessage());
        }
    }

    /**
     * 生成到流
     *
     * @param content
     * @param response
     */
    public void createQRCode2Stream(String content, int width, int height, HttpServletResponse response) {
        try {
            QrCodeUtil.generate(content, initQrConfig(width,height), "png", response.getOutputStream());
            log.info("生成二維碼成功!");
        } catch (QrCodeException | IOException e) {
            log.error("發生錯誤! {}!", e.getMessage());
        }
    }

3、編寫模擬controller

@RestController
@Slf4j
public class QRCodeController {
    @Autowired
    private QRCodeService qrCodeService;

    /**
     * 生成流的形式的二維碼
     * @param codeContent
     * @param response
     */
    @GetMapping("qrCode")
    public void getQRCode(String codeContent, int width, int height, HttpServletResponse response) {
        try {
            qrCodeService.createQRCode2Stream(codeContent, width, height, response);

            log.info("成功生成二維碼!");
        } catch (Exception e) {
            log.error("發生錯誤, 錯誤資訊是:{}!", e.getMessage());
        }
    }

    /**
     * 生成圖片並存放到本地
     * @param codeContent
     */
    @GetMapping("qrCodeByFile")
    public void getQRCodeByFile(String codeContent, int width, int height) {
        String filePath="G:/RPC/erweima/first.png";
        try {
            qrCodeService.createQRCode2File(codeContent,width,height,filePath);
            log.info("成功生成二維碼!");
        } catch (Exception e) {
            log.error("發生錯誤, 錯誤資訊是:{}!", e.getMessage());
        }
    }