java Spring Boot generates image QR code

First we need to introduce dependencies
and insert them into pom.xml

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.1</version>
</dependency>

Then write the function directly in the interface class

@GetMapping(value = "/qrcode/{text}")
public void generateQRCode(@PathVariable("text") String text, HttpServletResponse response) throws IOException, WriterException {
    
    
    response.setContentType(MediaType.IMAGE_PNG_VALUE);
    OutputStream outputStream = response.getOutputStream();

    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

    BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 200, 200, hints);
    MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

    outputStream.flush();
    outputStream.close();
}

Insert image description here
Then directly access the port+prefix configuration/qrcode/the QR code text content to be generated

For example, here I visit
http://localhost/books/qrcode/1992
and the interface will return a QR code to us. Because the CSDN platform does not support banning QR code images, I use a brush to crack it to avoid being harmonized,
Insert image description here
and then use my mobile phone Scan the QR code
Insert image description here
to bring out the content of our text

おすすめ

転載: blog.csdn.net/weixin_45966674/article/details/133016358