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

相关推荐
裕晟资质规划1 小时前
三类涉密资质延续时限差异分析:军工60日与集成印制3个月的边界
java·服务器·前端·网络·安全
念念清晰1 小时前
000-OpenJDK17 源码构建:MacOS环境(M芯片)
java·后端
Wang's Blog1 小时前
Java 项目实战: 交友项目 - 百度人脸识别入门案例
java·百度·交友
来福猿1 小时前
SpringCloud Config 源码分析:配置拉取、刷新与多环境管理
后端·spring·spring cloud
wuminyu2 小时前
JMM学习总结:深入理解happens-before关系
java·linux·c语言·jvm·c++
电商API_180079052472 小时前
反向海淘多币种结算:汇率该在哪个时点被冻结
java·开发语言·数据库·跨境电商·1688 api
古法老登瞎折腾2 小时前
大数据智能运维实战(一):机器和任务数据都有了,如何用 MCP 搭建运维助手?
大数据·运维·spring boot·spring ai·mcp
开开心心就好3 小时前
多份文档怎么批量打印?支持多种格式
java·服务器·开发语言·pdf·ocr·散列表·启发式算法
Pniubi3 小时前
模拟一个充值送token怎么保证幂等?一致性?原子性?
java
企业数字化笔记3 小时前
多租户配额怎么控制?用量口径、并发预留与超额处理的实现方法
java·数据库·spring boot