xxxxxxxxxx
package dev.simplesolution.generateqr.controller;
import dev.simplesolution.generateqr.service.QRCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
@Controller
public class QRCodeController {
@Autowired
private QRCodeService qrCodeService;
@RequestMapping("/")
public String index() {
return "index";
}
@PostMapping("/showQRCode")
public String showQRCode(String qrContent, Model model) {
model.addAttribute("qrCodeContent", "/generateQRCode?qrContent=" + qrContent);
return "show-qr-code";
}
@GetMapping("/generateQRCode")
public void generateQRCode(String qrContent, HttpServletResponse response) throws IOException {
response.setContentType("image/png");
byte[] qrCode = qrCodeService.generateQRCode(qrContent, 500, 500);
OutputStream outputStream = response.getOutputStream();
outputStream.write(qrCode);
}
}
xxxxxxxxxx
package dev.simplesolution.generateqr.service.impl;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import dev.simplesolution.generateqr.service.QRCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Service
public class QRCodeServiceImpl implements QRCodeService {
private Logger logger = LoggerFactory.getLogger(QRCodeServiceImpl.class);
@Override
public byte[] generateQRCode(String qrContent, int width, int height) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(qrContent, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
} catch (WriterException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}