Ja​​va使用 Zxing 编写二维码阅读器

x33g5p2x  于2021-10-17 转载在 Java  
字(2.3k)|赞(0)|评价(0)|浏览(254)

在上一篇文章中,我们学习了如何使用 google 的 Zxing 库在 java 中生成二维码。如果您还没有阅读我之前的教程,我鼓励您在阅读本教程之前先看一下。

在这篇文章中,我们将学习如何读取二维码图像并提取二维码中编码的数据。


使用您的智能手机扫描上述二维码。您将获得我网站的网址 - http://callicoder.com。我们将用 Java 编写一个类似的扫描器,您可以在其中传递二维码图像,程序将返回二维码中编码的数据。

在 Java 中读取二维码图像

我们将使用谷歌的 zxing 库来读取二维码图像。

请确保在您的 pom.xml 文件中添加了以下 zxing 依赖项 -

<!-- For Maven Users -->
<dependencies>
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>javase</artifactId>
        <version>3.3.0</version>
    </dependency>
</dependencies>

如果您使用的是 gradle,则添加以下依赖项 -

# For Gradle users
compile "com.google.zxing:core:3.3.0"
compile 'com.google.zxing:javase:3.3.0'

如果你没有使用任何构建系统,那么你可以直接在类路径中添加以下 zxing jars -

zxing core-3.3.0.jar
1.
zxing javase-3.3.0.jar

读取二维码图像的程序

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class QRCodeReader {

    private static String decodeQRCode(File qrCodeimage) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(qrCodeimage);
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        try {
            Result result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (NotFoundException e) {
            System.out.println("There is no QR code in the image");
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            File file = new File("MyQRCode.png");
            String decodedText = decodeQRCode(file);
            if(decodedText == null) {
                System.out.println("No QR Code found in the image");
            } else {
                System.out.println("Decoded text = " + decodedText);
            }
        } catch (IOException e) {
            System.out.println("Could not decode QR Code, IOException :: " + e.getMessage());
        }
    }
}

在上面的程序中,decodeQRCode() 函数获取一个图像文件并尝试读取图像中的任何二维码。如果找到 QR 码,则返回文本,否则返回 null。

### 结论

在这篇博文中,我们学习了如何使用 Zxing 库在 Java 中读取二维码。您可以在 my github repository 中找到所有代码示例。

Zxing 库还有一些其他有用的功能可供您使用。例如,使用 MultipleBarcodeReader 从图像中读取多个二维码。

查看 Zxing Github page 以获取有关图书馆的任何帮助。

另外,不要忘记探索 Zxing 在线二维码生成器和解码器应用程序 -

Zxing Online QR Code Generator
*
Zxing Online QR Code Decoder

相关文章

微信公众号

最新文章

更多