Maven依赖:
<!-- zxing 二维码生成 -->
<dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.2.1</version>
</dependency>
工具类:
package com.ypk.swagger.utils.auditUtils;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;/**** @author lgn* @date 2023/5/31 16:26*/
public class CommonUtils {public static String createQr(String link, Boolean isRemoveSide,String path) {if (link == null || link.length() <= 0) {System.err.println("链接地址不能为空");return "";}try {Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();// 指定编码格式hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数BitMatrix bitMatrix = new MultiFormatWriter().encode(link, BarcodeFormat.QR_CODE, 350, 350, hints);//去除白边if (isRemoveSide) {bitMatrix = deleteWhite(bitMatrix);}//以我的电脑为例//String path = "D://qr" + System.currentTimeMillis() + ".png";//设置请求头FileOutputStream fileOutputStream = new FileOutputStream(path);MatrixToImageWriter.writeToStream(bitMatrix, "png", fileOutputStream);fileOutputStream.close();return path;} catch (Exception e) {e.printStackTrace();}return "";}//去除二维码白边private static BitMatrix deleteWhite(BitMatrix matrix) {int[] rec = matrix.getEnclosingRectangle();int resWidth = rec[2] + 1;int resHeight = rec[3] + 1;BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);resMatrix.clear();for (int i = 0; i < resWidth; i++) {for (int j = 0; j < resHeight; j++) {if (matrix.get(i + rec[0], j + rec[1])) resMatrix.set(i, j);}}return resMatrix;}public static void main(String[] args) {String path = "/static/qr" + System.currentTimeMillis() + ".png";//存在白边String qr = createQr("https://www.baidu.com", false,path);//去除白边String qr1 = createQr("https://www.baidu.com", true,path);System.err.println(qr);System.err.println(qr1);}
}
本文链接:https://my.lmcjl.com/post/13120.html
展开阅读全文
4 评论