|
@@ -0,0 +1,75 @@
|
|
|
+package com.zhentao.order.controller;
|
|
|
+
|
|
|
+import com.google.zxing.BarcodeFormat;
|
|
|
+import com.google.zxing.MultiFormatWriter;
|
|
|
+import com.google.zxing.client.j2se.MatrixToImageWriter;
|
|
|
+import com.google.zxing.common.BitMatrix;
|
|
|
+import org.springframework.web.bind.annotation.*;
|
|
|
+
|
|
|
+import javax.imageio.ImageIO;
|
|
|
+import java.awt.image.BufferedImage;
|
|
|
+import java.io.ByteArrayOutputStream;
|
|
|
+import java.util.Base64;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+@RestController
|
|
|
+@RequestMapping("/api/qrcode")
|
|
|
+public class QrCodeController {
|
|
|
+
|
|
|
+ // 生成带用户数据的二维码接口
|
|
|
+ @PostMapping("/generate")
|
|
|
+ public Map<String, Object> generateQrCode(@RequestBody UserData userData) {
|
|
|
+ Map<String, Object> result = new HashMap<>();
|
|
|
+ try {
|
|
|
+ // 1. 处理用户数据
|
|
|
+ String dataToEncode = userData.toJsonString();
|
|
|
+
|
|
|
+ // 2. 生成二维码图片
|
|
|
+ int width = 300;
|
|
|
+ int height = 300;
|
|
|
+// 使用ZXIng ("Zebra Crossing")库来生成一个二维码图像
|
|
|
+ BitMatrix bitMatrix = new MultiFormatWriter().encode(dataToEncode, BarcodeFormat.QR_CODE, width, height);
|
|
|
+// 用于将bitMatrix变成图片
|
|
|
+ BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
|
|
|
+
|
|
|
+ // 3. 转换为Base64字符串
|
|
|
+// 这是一个输出流
|
|
|
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
|
+// 把对象写入到创建的输出流中
|
|
|
+ ImageIO.write(image, "png", baos);
|
|
|
+// 将字节数组转换成byte数组
|
|
|
+ byte[] imageBytes = baos.toByteArray();
|
|
|
+// 这个字符串可以方便地在文本环境中传输和存储图像数据
|
|
|
+ String base64Image = Base64.getEncoder().encodeToString(imageBytes);
|
|
|
+
|
|
|
+ // 4. 返回结果
|
|
|
+ result.put("success", true);
|
|
|
+ result.put("qrCodeUrl", "data:image/png;base64," + base64Image);
|
|
|
+ result.put("expireTime", System.currentTimeMillis() + 3600000); // 1小时有效期
|
|
|
+ } catch (Exception e) {
|
|
|
+ result.put("success", false);
|
|
|
+ result.put("message", "生成二维码失败: " + e.getMessage());
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+}
|
|
|
+class UserData {
|
|
|
+ private String userId;
|
|
|
+ private String name;
|
|
|
+ private long timestamp;
|
|
|
+
|
|
|
+ // getters and setters
|
|
|
+ public String getUserId() { return userId; }
|
|
|
+ public void setUserId(String userId) { this.userId = userId; }
|
|
|
+ public String getName() { return name; }
|
|
|
+ public void setName(String name) { this.name = name; }
|
|
|
+ public long getTimestamp() { return timestamp; }
|
|
|
+ public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
|
|
|
+
|
|
|
+ // 转换为JSON字符串(简化实现,实际建议用JSON库)
|
|
|
+ public String toJsonString() {
|
|
|
+ return String.format("{\"userId\":\"%s\",\"name\":\"%s\",\"timestamp\":%d}",
|
|
|
+ userId, name, timestamp);
|
|
|
+ }
|
|
|
+}
|