springboot 生成二维码
时间: 2023-08-07 11:12:04 浏览: 85
java Springboot 生成 二维码 +logo.docx
你可以使用第三方库生成二维码,比如zxing或者google的qrcode库。以下是使用zxing生成二维码的示例代码:
1. 添加依赖
```
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
```
2. 编写生成二维码的代码
```
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRCodeGenerator {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
private static final int QRCODE_SIZE = 300;
private static final int WIDTH = 60;
private static final int HEIGHT = 60;
private static void createImage(String content, String imgPath) throws Exception {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
File outputFile = new File(imgPath);
MatrixToImageWriter.writeToFile(bitMatrix, FORMAT_NAME, outputFile);
}
public static void main(String[] args) throws Exception {
String content = "https://www.baidu.com"; // 二维码内容
String imgPath = "C:/Users/Administrator/Desktop/qrcode.jpg"; // 生成的二维码图片路径
createImage(content, imgPath);
}
}
```
运行代码后,会在指定的路径生成一个二维码图片。
阅读全文