Front-end vue, jquery / background java to generate two-dimensional code

Posted by kripz on Tue, 01 Oct 2019 05:38:29 +0200

Recent projects need to develop the function of generating two-dimensional codes to facilitate the publicity and use of products, so I went to research, the following is the research results.

1. Using jquery to generate two-dimensional codes

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Two-Dimensional Code Testing</title>
    </head>
    <body> 
        <div id="qrcode" style="display: flex;justify-content: center;margin-top: 100px;"></div>
        
        <script type="text/javascript" src="js/jquery/jquery-2.1.4.min.js"></script>
        <script type="text/javascript" src="js/jquery.qrcode.min.js"></script>
        <script type="text/javascript">
            $('#qrcode').qrcode({
                text: "https://www.baidu.com/",//Content 
                height: 369,
                width: 369,  
                render: "canvas", //Rendering methods include table mode (IE compatible) and canvas mode.
                typeNumber:-1,//Computing mode
                background: "#ffffff ",//background color
                foreground: "#000 000", //2-D code color
                correctLevel: QRCode.correctLevel,//Error Correction Level L: 1, M: 0, Q: 3, H: 2 (Default)
                src: 'img/icon/r-VY-hpinrya9109218.jpg'//logo
            })
        </script>
    </body>
    
</html>

Look at the jquery.qrcode.min.js source code to see

Generated two-dimensional code

2. Using vue to generate two-dimensional codes

1) Install vue-qr using npm and introduce vue-qr after success

npm install vue-qr --save

import VueQr from 'vue-qr'

2) Implementation code

<template>
  <div class="qr-code-box">
    <vue-qr :logoSrc="config.logo" :text="config.value" class="qr-code-pic" :correctLevel="3" :margin="0"
            :dotScale="0.5"></vue-qr>
  </div>
</template>

<script>
  import VueQr from 'vue-qr';

  export default {
    data() {
      return {
        config: {
          value: '',
          logo: require('./r-VY-hpinrya9109218.jpg')
        }
      }
    },
    mounted() {
      this.config.value = "https://www.baidu.com/";
    },
    components: {
      VueQr
    }
  }
</script>

<style scoped>
  .qr-code-box{
    display: flex;
    justify-content: center;
    margin-top: 100px;
  }
  .qr-code-pic{
    width: 300px;
    height: 300px;
  }
</style>

3) Parameter Configuration
Correct Level 0-3 Fault Tolerance Level 0-3
logoSrc Embedded in LOGO Address of Two-Dimensional Code Center
Dot Scale data area point reduction ratio, default 0.35
.......
Can see https://www.npmjs.com/package...

Generating two-dimensional codes

3. Generating two-dimensional code by Java

1) Importing maven dependencies

<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.1</version>
</dependency>

2) Implementation code

package com.example.spring.controller;

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;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * Drawing logo and drawing two-dimensional code for description
 */
@RestController
public class ZXingCodeController {
    private static Logger logger = LoggerFactory.getLogger(ZXingCodeController.class);

    private static final int QRCOLOR = 0xFF000000; // The default is black
    private static final int BGWHITE = 0xFFFFFFFF; // background color

    private static final int WIDTH = 400; // Two dimensional code width
    private static final int HEIGHT = 400; // Two dimensional code height

    @GetMapping("/create_zx_code")
    public void createCode(String[] args) throws WriterException {
        File logoFile = new File("D://logo.jpg");
        File QrCodeFile = new File("D://qrcode.png");
        String url = "https://www.baidu.com/";
        String note = "Visit Baidu connection";
        drawLogoQRCode(logoFile, QrCodeFile, url, note);
    }

    // Used to set QR two-dimensional code parameters
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// Setting the Error Correction Level (H is the highest level) Specific Level Information for QR Two-Dimensional Codes
            put(EncodeHintType.CHARACTER_SET, "utf-8");// Set encoding mode
            put(EncodeHintType.MARGIN, 0);
        }
    };

    // Generating two-dimensional code picture with logo
    public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // The parameters are: encoding content, coding type, generating image width, generating picture height, setting parameters.
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // Begin to create Bitmap images using two-dimensional code data, set to black (0xFFFFFFFF FFFFFF) and white (0xFF000000) respectively.
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            int width = image.getWidth();
            int height = image.getHeight();
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                // Constructing Drawing Objects
                Graphics2D g = image.createGraphics();
                // Read Logo Pictures
                BufferedImage logo = ImageIO.read(logoFile);
                // Start drawing logo pictures
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }

            // Custom Text Description
            if (StringUtils.isNotEmpty(note)) {
                // New picture, add text under the two-dimensional code with logo
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // Draw two-dimensional code to the new panel
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // Draw text to a new panel
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("Regular script", Font.BOLD, 30)); // Font, font, font size
                int strWidth = outg.getFontMetrics().stringWidth(note);
                if (strWidth > 399) {
                    // // If the length is too long, intercept the front part
                    // Change lines if the length is too long
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("Song style", Font.BOLD, 30)); // Font, font, font size
                    outg2.drawString(note2, 200 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // Draw text
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }

            image.flush();

            ImageIO.write(image, "png", codeFile);
            logger.info("Completion of generating two-dimensional codes");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Look at the log for running results

3) Generating two-dimensional codes

This is the summary of the way to generate two-dimensional codes. I hope you can benefit from the bad writing.

Topics: Javascript Google QRCode Vue Java