1.引入依赖包
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
2.代码正文:
package com.test.common.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class QrCodeUtil {
public static byte[] generateQrCode(String content,int width, int height, String imageType) throws WriterException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
MatrixToImageWriter.writeToStream(bitMatrix, imageType, byteArrayOutputStream);
QrCodeUtil.generateQrCode("https://www.baidu.com/", 200, 200, "PNG");
String base64Image = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
System.out.println("data:image/png;base64," + base64Image);
// 这里是工具类,需要接口直接返回的话使用上面打印出来的base64格式
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException("Failed to generate QR Code", e);
}
}
}