Java 生成在線二維碼 以Base64返回前端

依賴的jar包主要是Google 的zxing 進行二維碼的生成

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

 

 

第一種生成base64編碼返回前端

package com.mingwen.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.utils.qrcode.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeUtil {
    private static String base64Url = "data:image/png;base64,";

    /**
     * 創建二維碼
     * 
     * @param url
     * @param fileName
     * @return
     * @throws IOException
     * @throws WriterException
     */
    public static String createQRCode(String json) throws IOException, WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(json, BarcodeFormat.QR_CODE, 600, 600, hints);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        Base64.Encoder encoder = Base64.getEncoder();
        String text = encoder.encodeToString(outputStream.toByteArray());
        return base64Url + text;
    }

    public static void main(String[] args) throws IOException, WriterException {
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        json.put("name", "吳順傑");
        json.put("phone", "手機號碼");
        json.put("address", "地址");
        json.put("bookid", "64");
        for (int i = 0; i < 3; i++) {
            JSONObject jsonw = new JSONObject();
            jsonw.put("id", i);
            jsonw.put("count", i);
            jsonw.put("remake", "哈哈哈");
            arr.add(jsonw);
            json.put("Books", arr);

        }
        System.out.println(json);
        System.out.println(createQRCode(json.toString()));
    }
}

通過base64轉二維碼(http://tool.chinaz.com/tools/imgtobase/

 

用微信掃描二維碼:

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章