登录
首页 >  Golang >  Go教程

Golang生成二维码工具实例教程

时间:2025-09-30 11:54:48 462浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《Golang生成扫描二维码工具示例》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

Go语言利用go-qrcode和gozxing库可实现二维码生成与扫描,通过命令行工具整合功能,支持文本编码为PNG图像及图像中二维码的解码识别,适用于轻量级应用开发。

Golang实现二维码生成与扫描工具示例

Go语言(Golang)凭借其简洁的语法和高效的并发支持,非常适合开发轻量级工具类应用。实现一个二维码生成与扫描工具,既能满足日常需求,也能展示Go在文件处理、图像操作和命令行交互方面的优势。下面通过 qrcodegozxing 两个主流库,演示如何用Golang完成二维码的生成与识别。

1. 安装依赖库

项目需要两个核心库:
  • github.com/skip2/go-qrcode:用于生成二维码图片
  • github.com/makiuchi-d/gozxing 及其子包:用于解码二维码图像

执行以下命令安装:

go mod init qrcode-tool
go get github.com/skip2/go-qrcode
go get github.com/makiuchi-d/gozxing
go get github.com/makiuchi-d/gozxing/qr

2. 生成二维码

使用 go-qrcode 可以快速将文本内容编码为PNG图像。以下函数将指定内容写入本地文件:

package main

import (
    "log"
    "github.com/skip2/go-qrcode"
)

func generateQR(content, filename string) {
    err := qrcode.WriteFile(content, qrcode.Medium, 256, filename)
    if err != nil {
        log.Fatalf("生成二维码失败: %v", err)
    }
    log.Printf("二维码已保存为 %s", filename)
}
调用示例:
generateQR("https://example.com", "qrcode.png")

参数说明:content为要编码的内容,filename是输出文件名,256表示图像尺寸(像素),Medium为纠错等级。

3. 扫描二维码

借助 gozxing 库读取图像并解析其中的二维码信息:

package main

import (
    "os"
    "log"
    "image/png"

    "github.com/makiuchi-d/gozxing"
    "github.com/makiuchi-d/gozxing/qr"
    "github.com/makiuchi-d/gozxing/multi/qrcode"
    "github.com/makiuchi-d/gozxing/common/detector"
)

func decodeQR(filename string) {
    file, err := os.Open(filename)
    if err != nil {
        log.Fatalf("打开文件失败: %v", err)
    }
    defer file.Close()

    img, err := png.Decode(file)
    if err != nil {
        log.Fatalf("解码图像失败: %v", err)
    }

    // 构建二值化图像源
    binImg := gozxing.NewBinaryBitmap(gozxing.NewHybridBinarizer(gozxing.NewLuminanceSourceFromImage(img)))

    // 使用QR码解码器
    qrReader := qr.NewQRCodeReader()
    result, err := qrReader.Decode(binImg, nil)
    if err != nil {
        // 尝试多二维码探测
        detector := detector.NewDetector(gozxing.NewLuminanceSourceFromImage(img))
        qrCodes, _ := qrcode.Detect(detector)
        if qrCodes == nil {
            log.Fatal("未检测到二维码")
        }
        for _, code := range qrCodes.GetResultPoints() {
            log.Printf("发现二维码位置: %v", code)
        }
        log.Fatal("无法解码二维码内容")
    }

    log.Printf("解码结果: %s", result.GetText())
}
调用示例:
decodeQR("qrcode.png")

该函数会输出图像中包含的文本内容,例如URL或纯文本。

4. 命令行工具整合

将功能封装为主程序,支持通过命令行参数选择生成或扫描:

func main() {
    if len(os.Args) < 2 {
        log.Fatal("用法: qrcode-tool encode '内容' 或 qrcode-tool decode 图片路径")
    }

    mode := os.Args[1]

    switch mode {
    case "encode":
        if len(os.Args) != 3 {
            log.Fatal("生成模式需提供内容")
        }
        generateQR(os.Args[2], "out.png")
    case "decode":
        if len(os.Args) != 3 {
            log.Fatal("扫描模式需提供文件路径")
        }
        decodeQR(os.Args[2])
    default:
        log.Fatal("不支持的模式,使用 encode 或 decode")
    }
}

编译运行:

go build -o qrcode-tool
./qrcode-tool encode "Hello, QR Code!"
./qrcode-tool decode out.png

第一条命令生成二维码图片,第二条读取并打印内容。

基本上就这些。Golang结合成熟库能快速构建实用的二维码工具,无需依赖外部服务,适合嵌入到更大系统中使用。整个流程不复杂但容易忽略图像格式兼容性和错误处理细节。合理封装后可用于配置分发、身份绑定等场景。

理论要掌握,实操不能落!以上关于《Golang生成二维码工具实例教程》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>