Java uses zxing.jar to generate QR codes

1) Create a maven project and import the zxing dependency package in pom.xml

<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.3.0</version>
        <exclusions>
            <exclusion>
                <artifactId>core</artifactId>
                <groupId>com.google.zxing</groupId>
            </exclusion>
        </exclusions>
</dependency>

2) Create a test class TestController, the code is as follows

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


import com.google.zxing.client.j2se.MatrixToImageWriter;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


@RestController
public class TestController {

    // 生成二维码
    @RequestMapping("/getCode") 
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); 
            // Set the QR code encoding character set 
            hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
    public void getCode(HttpServletResponse response){ 
        // QR code content 
        String contents = " Baidu, you will know "; 
        // Indicates that it is a QR code 
        BarcodeFormat qrCode = BarcodeFormat.QR_CODE; 
        // QR code width 
        int width = 300 ; 
        // The height of the QR code 
        int height = 300; 
        // The returned image format 
        String format = "png"; 
        response.setContentType("image/png"); 
        try { 
            // Set the outer spacing of the QR code 
            hints.put (EncodeHintType.MARGIN, 10); 
            // Set the QR code error tolerance level 
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 
            // Create a QR code object 
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, qrCode, width, height, hints); 
            / / Output QR code 
            MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream()); 
        } catch (WriterException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
    } 
}

Guess you like

Origin blog.csdn.net/m0_52191385/article/details/130966653