在现代应用中,读取二维码中的信息是一个常见的需求。本文将介绍如何在 Spring Boot 项目中实现从上传的二维码图片中读取包含的信息,包括引入 ZXing 依赖、实现读取二维码信息的方法、编写处理上传文件的控制器,并提供详细的代码示例。
1. 引入依赖
首先,在 Spring Boot 项目的 pom.xml 文件中引入 ZXing 相关的依赖:
bash
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.3</version>
</dependency>
2. 实现读取二维码信息的方法
创建一个服务类 QRCodeProcessingService 的服务类,用于从上传的二维码图片中提取信息:
bash
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Service
public class QRCodeProcessingService {
public String extractQRCodeText(MultipartFile file) throws IOException, NotFoundException {
try (InputStream inputStream = file.getInputStream()) {
BufferedImage bufferedImage = ImageIO.read(inputStream);
if (bufferedImage == null) {
throw new IOException("Could not decode image from input stream");
}
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
Map<DecodeHintType, Object> hintMap = new HashMap<>();
hintMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hintMap);
return qrCodeResult.getText();
}
}
}
3.创建控制器类处理文件上传
然后,创建一个名为 QRCodeUploadController 的控制器类,处理上传文件并调用 QRCodeProcessingService 的方法:
bash
import com.google.zxing.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
public class QRCodeUploadController {
@Autowired
private QRCodeProcessingService qrCodeProcessingService;
@PostMapping("/uploadQRCode")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
String decodedText = qrCodeProcessingService.extractQRCodeText(file);
if (decodedText == null) {
return new ResponseEntity<>("Could not decode QR Code", HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(decodedText, HttpStatus.OK);
} catch (IOException | NotFoundException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
完整代码结构
bash
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── qrcode
│ │ ├── controller
│ │ │ └── QRCodeUploadController.java
│ │ ├── service
│ │ │ └── QRCodeProcessingService.java
│ │ └── QRCodeApplication.java
│ └── resources
│ └── application.yml
使用前端页面上传二维码图片并读取信息
启动 Spring Boot 应用程序,在前端页面中提供上传功能,用户可以上传包含二维码的图片文件,并从中读取信息。
bash
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload QR Code Image</title>
</head>
<body>
<h2>上传二维码图片并读取信息</h2>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="fileInput" name="file" accept="image/*">
<button type="submit">上传图片</button>
</form>
<div id="result"></div>
<script>
document.getElementById('uploadForm').addEventListener('submit', function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('file', document.getElementById('fileInput').files[0]);
fetch('/uploadQRCode', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('result').innerText = data;
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
</body>
</html>
请求参数:
- file: 上传的二维码图片文件。
总结
本文介绍了如何在Spring Boot项目中使用ZXing库从上传的二维码图片中提取信息。通过配置依赖、创建服务类和控制器类,我们实现了二维码信息的读取和展示。这种方法可以帮助我们在各种应用场景中读取二维码中的信息,便于数据获取和处理。