package com.bofeng.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class QrController {

    @GetMapping(value = "/admin/qr.png", produces = MediaType.IMAGE_PNG_VALUE)
    public void getQRCode(@RequestParam("text") String text, HttpServletResponse response) throws WriterException, IOException {

        ServletOutputStream outputStream = response.getOutputStream();
        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 256, 256);
        MatrixToImageWriter.writeToStream(matrix, MediaType.IMAGE_PNG.getSubtype(), outputStream, new MatrixToImageConfig());
    }

    @GetMapping(value = "/admin/qr2.png", produces = MediaType.IMAGE_PNG_VALUE)
    public void getQRCode2(@RequestParam("text") String text, HttpServletResponse response) throws WriterException, IOException {

        ServletOutputStream outputStream = response.getOutputStream();
        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 430, 430);
        MatrixToImageWriter.writeToStream(matrix, MediaType.IMAGE_PNG.getSubtype(), outputStream, new MatrixToImageConfig());
    }
}
