前端vue、jquery/後臺java實現生成二維碼

最近項目中須要開發生成二維碼的功能,便於宣傳和使用產品,因而便去研究一番,如下是研究的成果javascript

1.使用jquery生成二維碼

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>二維碼測試</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/",//內容 
                height: 369,
                width: 369,  
                render: "canvas", //渲染方式有table方式(IE兼容)和canvas方式
                typeNumber:-1,//計算模式
                background: "#ffffff",//背景顏色
                foreground: "#000000",//二維碼顏色
                correctLevel: QRCode.correctLevel,//二維碼糾錯級別 L: 1,M: 0,Q: 3,H: 2(默認)
                src: 'img/icon/r-VY-hpinrya9109218.jpg'//logo
            })
        </script>
    </body>
    
</html>

查看jquery.qrcode.min.js源碼能夠看出
圖片描述
生成的二維碼
圖片描述html

2.使用vue生成二維碼

1)使用npm安裝vue-qr,成功後引入vue-qrvue

npm install vue-qr --save

import VueQr from 'vue-qr'

2)實現代碼java

<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)參數配置
Correct Level 0-3 容錯級別 0-3
logoSrc 嵌入至二維碼中心的 LOGO 地址
dotScale 數據區域點縮小比例,默認爲0.35
.......
能夠看https://www.npmjs.com/package...jquery

生成二維碼
圖片描述web

3.java生成二維碼

1)導入maven依賴spring

<!-- 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)實現代碼apache

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;


/**
 * 畫制定logo和制定描述的二維碼
 */
@RestController
public class ZXingCodeController {
    private static Logger logger = LoggerFactory.getLogger(ZXingCodeController.class);

    private static final int QRCOLOR = 0xFF000000; // 默認是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景顏色

    private static final int WIDTH = 400; // 二維碼寬
    private static final int HEIGHT = 400; // 二維碼高

    @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 = "訪問百度鏈接";
        drawLogoQRCode(logoFile, QrCodeFile, url, note);
    }

    // 用於設置QR二維碼參數
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 設置QR二維碼的糾錯級別(H爲最高級別)具體級別信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 設置編碼方式
            put(EncodeHintType.MARGIN, 0);
        }
    };

    // 生成帶logo的二維碼圖片
    public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 參數順序分別爲:編碼內容,編碼類型,生成圖片寬度,生成圖片高度,設置參數
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 開始利用二維碼數據建立Bitmap圖片,分別設爲黑(0xFFFFFFFF)白(0xFF000000)兩色
            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()) {
                // 構建繪圖對象
                Graphics2D g = image.createGraphics();
                // 讀取Logo圖片
                BufferedImage logo = ImageIO.read(logoFile);
                // 開始繪製logo圖片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }

            // 自定義文本描述
            if (StringUtils.isNotEmpty(note)) {
                // 新的圖片,把帶logo的二維碼下面加上文字
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 畫二維碼到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 畫文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("楷體", Font.BOLD, 30)); // 字體、字型、字號
                int strWidth = outg.getFontMetrics().stringWidth(note);
                if (strWidth > 399) {
                    // //長度過長就截取前面部分
                    // 長度過長就換行
                    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("宋體", Font.BOLD, 30)); // 字體、字型、字號
                    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); // 畫文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }

            image.flush();

            ImageIO.write(image, "png", codeFile);
            logger.info("生成二維碼完畢");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

運行結果看日誌
圖片描述
3)生成二維碼
圖片描述npm

以上即是此次對二維碼生成方式總結,寫的很差地方望指點,但願你們能受益canvas

相關文章
相關標籤/搜索