ZXing+SpringMvc generates a QR code image and renders it to the front page

In real life, many places need to use QR code, WeChat public account, payment, APP download, etc. can use the QR code as the entrance, and you can get the desired result by scanning it. Generally speaking, QR codes are static. After generating the QR code image directly through the QR code generation tool, the static image is directly embedded in the web page. The current business requirement is that the APK is constantly updated. You cannot generate a QR code every time the APP version is updated, and your server address may also change, so the QR code is not fixed. . For programmers, it is a bit troublesome to use tools to generate QR codes every time, and they will definitely consider some once-and-for-all methods. This article is to introduce the realization of this function.


The first thing to consider is to use a front-end js framework such as jQuery-qrcode.js with high stars on github, or qrcode.js. This is also a good method. However, the front desk of this article uses react.js, which does not have a QR code generation framework compatible with ES6, so consider obtaining QR code images from the background.


Java is used in the background, and there are various choices of jar packages for Java to generate QR codes. For example, the famous com.google.zxing, this article uses this toolkit. First import this package under maven

- <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>


Since it is a downloaded file, you can use SpringMVC's ResponseEntity, and the generic type is byte[]. You can also use the original HttpServletResponse to download files. This article uses ResponseEntity.


Then you can directly encapsulate a method for downloading QR code pictures.

/**
     * Generate and download QR code
     * @param url QR code for URL
     * @param width QR code width
     * @param height QR code height
     * @param format QR code format
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static ResponseEntity<byte[]> getResponseEntity(String url,int width, int height,String format) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url,
                BarcodeFormat.QR_CODE, width, height, hints);// Generate matrix
        // Convert the matrix to Image
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, format, out);//Convert BufferedImage to out output stream
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(out.toByteArray(),
                headers, HttpStatus.CREATED);
    }
Then you can call it directly, for example:

@RequestMapping("/downloadIOSAPPQRCode")
    public ResponseEntity<byte[]> downloadIOSAPPController(@RequestParam(required = true)String type)
            throws WriterException, IOException{
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("app.properties");
        Properties props = new Properties();
        props.load(is);
        String appId = (String)props.get(type);
        String url = Constants.APP_STORE_SUFFIX + appId;
        return DownloadUtil.getResponseEntity(url, 150, 150, "png");
    }

The front desk directly applies this interface

<img src={baseURL + '/downloadIOSAPPQRCode?type=teacher'}/>

properties file can be placed in the resource directory

The app.properties file is as follows

Patriarch-APP-ID=1213271782
Teacher-APP-ID=1213271782
      
         Pay attention to the WeChat public account and learn a little programmer's professional experience every day


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640757&siteId=291194637