java 解析二维码工具类

mavn pom.xml

复制代码
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.5.3</version>
</dependency>

java 测试类

java 复制代码
import com.google.zxing.BinaryBitmap;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class QRCodeReader {

    public static String decodeQRCode(String filePath) {
        try {
            BufferedImage bufferedImage = ImageIO.read(new File(filePath));
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
            Result result = new MultiFormatReader().decode(binaryBitmap);
            return result.getText();
        } catch (NotFoundException e) {
            System.err.println("No QR code found in the image.");
        } catch (IOException e) {
            System.err.println("Error reading the image file: " + e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        String filePath = QRCodeReader.class.getResource("/861393067237070.png").getPath();
        String qrCodeText = decodeQRCode(filePath);
        if (qrCodeText != null) {
            System.out.println("Decoded QR Code: " + qrCodeText);
        } else {
            System.out.println("Failed to decode QR code.");
        }
    }
}

重点关注:

main方法

相关推荐
爱吃烤鸡翅的酸菜鱼12 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
惊涛骇浪、18 分钟前
SpringMVC + Tomcat10
java·tomcat·springmvc
chao_78920 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
然我21 分钟前
不用 Redux 也能全局状态管理?看我用 useReducer+Context 搞个 Todo 应用
前端·javascript·react.js
前端小巷子26 分钟前
Web 实时通信:从短轮询到 WebSocket
前端·javascript·面试
神仙别闹29 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
墨染点香31 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
web前端神器36 分钟前
指定阿里镜像原理
前端
枷锁—sha40 分钟前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
枷锁—sha42 分钟前
跨站请求伪造漏洞(CSRF)详解
运维·服务器·前端·web安全·网络安全·csrf