Java 生成在线二维码 以Base64返回前端

2 篇文章 0 订阅
1 篇文章 0 订阅

依赖的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/

 

用微信扫描二维码:

 

 

 

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值