1、idea中引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version> <!-- 或者你项目中所需的版本 -->
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version> <!-- 或者你项目中所需的版本 -->
</dependency>
2、java类
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;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class QRCodeController {
@GetMapping("/generateQRCode")
public ResponseEntity<?> generateQRCode(HttpServletRequest request) {
try {
// 生成二维码内容
String qrCodeData = request.getParameter("url");
// 设置过期时间(10分钟后)
long expirationTime = System.currentTimeMillis() + (10 * 60 * 1000);
// 将过期时间添加到二维码内容中
qrCodeData += "?expires=" + expirationTime;
// 设置二维码的宽度和高度
int width = 300;
int height = 300;
// 设置二维码参数
HashMap<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 使用ZXing生成二维码矩阵
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, width, height, hints);
// 将BitMatrix转换为BufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics();
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.BLACK);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (bitMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
// 将BufferedImage转换为字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
byte[] imageBytes = baos.toByteArray();
// 将字节数组转换为Base64编码的字符串
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
// 返回包含Base64编码的二维码的响应
Map<String, String> response = new HashMap<>();
response.put("qrCode", base64Image);
response.put("expires", String.valueOf(expirationTime));
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(response);
} catch (WriterException | IOException e) {
e.printStackTrace();
return ResponseEntity.badRequest().body("Failed to generate QR code.");
}
}
}
3、前端代码(我自己写的,比较简单,仅供参考)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>生成二维码</title> </head> <body> <h1>生成二维码</h1>
<!-- 输入文本内--> <input type="text" id="tx"> <button οnclick="gerQRCode2()">点我生成二维码2</button> <img id="img"> </body> <script> function getQRcode(){ var tx = document.getElementById("tx"); var content = tx.value; document.getElementById("img").src="http://localhost:8080/generateQRCodeEasy?url="+content; } function gerQRCode2(){ var img = document.getElementById("img"); // 创建 XMLHttpRequest 对象 var xhr = new XMLHttpRequest(); var content=document.getElementById("tx").value; // 设置请求方法和URL xhr.open("GET", "http://localhost:8080/generateQRCode?url="+content, true); // 监听请求状态变化 xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { // 请求成功,解析 JSON 响应数据 var responseData = JSON.parse(xhr.responseText); // 访问 JSON 中的指定参数 var specificParam = responseData.qrCode; // 假设 JSON 中有一个名为 "key" 的参数 // 进行后续操作 // 设置 Image 对象的 src 属性为 Base64 字符串 img.src = "data:image/png;base64," + specificParam; // console.log("Value of specificParam:", specificParam); } else { // 请求失败,处理错误 console.error("Request failed with status:", xhr.status); } } }; // 发送请求 xhr.send(); } </script> </html>
4、效果 是一个二维码,扫一扫后里面的内容是你输入的文本内容