二维码扫描是我们在开发中常见的业务,要说识别率最高的、免费的、开源的 肯定是openCV的 但是这个博主在使用的时候发现了一个问题 就是本地调试是正常的,发到服务器上却提示缺少依赖包。博主经过多方面排查并且尝试很多种方案,最终才解决。这个比较麻烦,所以今天给大家提供另一个版本的识别方法,Boofcv版。 这个版本的识别率比Zxing的高且简单易懂 大家可以试试。
好了废话不多的,直接上代码。
1.添加相关依赖包
<dependency>
<groupId>org.boofcv</groupId>
<artifactId>boofcv-core</artifactId>
<version>0.33</version>
</dependency>
2.使用示例
package com.example.demotest.dingding;
import boofcv.abst.fiducial.QrCodeDetector;
import boofcv.factory.fiducial.FactoryFiducial;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.image.GrayU8;
import lombok.var;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
/**
* @author: Mr.Z
* @create: 2025-09-09 09:11
**/
@RestController
@RequestMapping("/erweima")
public class erweima {
/**
* BoofCV 版本
*
* @param file
* @return
*/
@PostMapping("/analyzeTwoDimensionalCode")
public String decodeQRCode(@RequestParam("file") MultipartFile file) {
//获取文件后缀名
String originalFilename = file.getOriginalFilename();
List<String> originalList = Arrays.asList("jpg", "JPG", "png", "PNG", "jpeg", "JPEG");
String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (!originalList.contains(substring)) {
return "文件格式错误,只允许使用jpg、png、jpeg格式文件";
}
try {
// 将上传的文件转换为BufferedImage
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null) {
throw new IllegalArgumentException("上传的文件不是有效的图片");
}
// 转换为BoofCV需要的格式
GrayU8 gray = ConvertBufferedImage.convertFrom(image, (GrayU8) null);
// 创建二维码检测器
QrCodeDetector<GrayU8> detector = FactoryFiducial.qrcode(null, GrayU8.class);
detector.process(gray);
// 获取检测结果
var detections = detector.getDetections();
if (!detections.isEmpty()) {
return detections.get(0).message;
} else {
return "未检测到二维码";
}
} catch (Exception e) {
e.printStackTrace();
return "解析二维码出错,请使用清晰的二维码图片进行尝试";
}
}
}
本文如果帮助到您了 请动用您发财的小手点点赞!
2141

被折叠的 条评论
为什么被折叠?



