java creates two dimensional code and gives url link function realization

  • 2021-10-11 18:26:56
  • OfStack

First import the dependencies in the pom file


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

Tool class


public class YmtUtil {
   public static byte[] getQRCodeImage(String text, int width, int height) throws 
        WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, 
        height);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray();
        return pngData;
}

Function realization

Here is the code written in service. After calling, you can find the corresponding 2-D code in the specified storage location


// Gets the value to be assigned to 2 The link suffix of dimension code is such as  192.168.0.21/erweima
String url = erweima;
 
// Get native ip Address, you can also find it 1 Specify ip The address is written to death 
InetAddress localhost = StrUtil.getLocalHostExactAddress();
 
// Settings 2 Dimension code access path 
String URL= "http://localhost"+ url;
 
// Settings 2 Dimensional code stream 
qrcode = YmtUtil.getQRCodeImage(URL, 360, 360);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
 
// Set the generated 2 Dimension code storage address  linux Path: ( /root/D:/opt/upFiles )   window Path ( D:/opt/upFiles ) Used here is the linux Path 
File path = new File("/root/D:/opt/upFiles", 2 Dimension code name  + ".jpg");
 
// Will 2 Convert binary array to file 
ByteArrayInputStream inputStream = new ByteArrayInputStream(qrcode);
MockMultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
file.transferTo(path);

The above is java to create 2-D code and give url link details, more information about java to create 2-D code please pay attention to other related articles on this site!


Related articles: