1.引入依赖
<!-- 二维码解析需要 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.3</version>
</dependency>
2.编写Controller层代码
import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/qrlogin")
public class QrLoginController {
// 二维码解析接口
@PostMapping("/decode")
public Map<String, String> decodeQrCode(@RequestPart("file") MultipartFile file) {
Map<String, String> resultMap = new HashMap<>();
try {
// 将MultipartFile转成BufferedImage
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
// 使用ZXing解析二维码
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(bufferedImage)));
Result result = new MultiFormatReader().decode(binaryBitmap);
resultMap.put("status", "success");
resultMap.put("content", result.getText());
} catch (Exception e) {
resultMap.put("status", "error");
resultMap.put("message", "解析二维码失败:" + e.getMessage());
}
return resultMap;
}
// 你的原本生成二维码的接口保持不变
@GetMapping("/generate")
public void generateQrCode(@RequestParam(required = false) String rand, HttpServletResponse response)
throws IOException, WriterException {
String uuid = UUID.randomUUID().toString();
String qrContent = "https://your-app-domain/login?uuid=" + uuid;
System.out.println(uuid);
int width = 300;
int height = 300;
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
BitMatrix bitMatrix = new MultiFormatWriter()
.encode(qrContent, BarcodeFormat.QR_CODE, width, height, hints);
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setContentType("image/png");
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
}
}
3.二维码生成
4.二维码解析
保存生成二维码,图片上传到解析接口