<!-- 引入jar包 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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;
/**
* <p>
* 生成二维码的工具类
* </p>
*
* @author lg
* @date 2020年12月15日
*/
public class QRCodeUtils {
/**
* 生成二维码
*
* @param content 二维码的内容
* @return BitMatrix对象
*
*/
public static BitMatrix createCode(String content) throws IOException {
// 二维码的宽高
int width = 200;
int height = 200;
// 其他参数,如字符集编码
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 容错级别为H
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 白边的宽度,可取0~4
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = null;
try {
// 生成矩阵,业务场景传来的是编码之后的URL,所以先解码
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// bitMatrix = deleteWhite(bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
}
return bitMatrix;
}
/**
* 删除生成的二维码周围的白边,根据审美决定是否删除
*
* @param matrix BitMatrix对象
* @return BitMatrix对象
*/
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;
}
}
//生成二维码
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//二维码内容
String content = "";
//获取一个二维码图片
BitMatrix bitMatrix = QRCodeUtils.createCode(content);
//以流的形式输出到前端
MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , bos);
String suffix = ".jpg";
//图片上传
String url = localStorageService.fileUpload(bos.toByteArray(), suffix);
图片上传接口 请查看之前的文章 <springboot文件上传>