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/)
用微信扫描二维码: