Spring Boot :从上传的二维码图片中读取信息

在现代应用中,读取二维码中的信息是一个常见的需求。本文将介绍如何在 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库从上传的二维码图片中提取信息。通过配置依赖、创建服务类和控制器类,我们实现了二维码信息的读取和展示。这种方法可以帮助我们在各种应用场景中读取二维码中的信息,便于数据获取和处理。

相关推荐
渔夫正在掘金4 小时前
Cordis 插件热插拔能力深度解析
后端·node.js
不爱编程的小九九4 小时前
小九源码-springboot004-springboot智能阅读推荐系统
java·spring boot·后端
码事漫谈4 小时前
为什么调试模式不崩溃,打包后却崩溃了?
后端
AC赳赳老秦5 小时前
OpenClaw 多源采集公开行业数据:从原始信息到研究报告初稿的自动化实践
java·c语言·c++·python·php·deepseek·openclaw
智驭未来掌门人5 小时前
利用FFmpeg快速实现一个RTSP推流服务器
后端
垚垚学技术_聚焦云原生5 小时前
K8s Pod 完整生命周期详解
后端
JavaGuide5 小时前
Github 史诗级故障,与此同时,Cursor 版「GitHub」正式上线!
前端·后端
Java成神之路-5 小时前
深入理解三大高频队列:ArrayDeque、LinkedList、PriorityQueue 方法、特性与场景选择
java
不一样的少年_5 小时前
修了 Bug、做了重构,为什么老板还是觉得你没产出?
前端·后端·程序员
roman_日积跬步-终至千里5 小时前
【资源控制】自助查询的智能路由
java·大数据·数据库