qrcode

package module
v0.0.0-...-307ed3b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: GPL-3.0 Imports: 12 Imported by: 97 modules, 94 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

qrcode

Go Reference Go Version

A pure-Go QR code decoder: hand it an image and it returns the decoded payload. No CGO, no external binaries, no separate image pipeline — image loading comes from the standard library, error correction from a small Reed–Solomon package.

English | 简体中文

Features

  • Real-world images — screenshots, camera photos, screen captures with logos/glare, JPEG artifacts.
  • Every version and EC level — QR versions 1–40, error-correction levels L/M/Q/H.
  • Every data mode — numeric, alphanumeric, 8-bit byte, and Kanji (Shift JIS decoded to UTF-8).
  • Rotation — arbitrary rotation handled by affine sampling anchored on the three finder patterns.
  • Perspective — homography sampling from the alignment pattern (versions ≥ 2); version 1 falls back to affine.
  • Adaptive binarization — Otsu threshold computed per image, so uneven lighting needs no tuning.
  • Error correction — block deinterleaving plus Reed–Solomon correction.
  • Inverted and dot-style symbols — light-on-dark and non-connected ("art") codes decode through a scanline 1:1:3:1:1 fallback.
  • Fast on large photos — finders are detected on a downscaled grid while modules are sampled from full-resolution pixels.

Installation

go get github.com/tuotoo/qrcode

Requires Go 1.27 or newer.

Quick start

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/tuotoo/qrcode"
)

func main() {
	f, err := os.Open("qrcode1.png")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	m, err := qrcode.Decode(f)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(m.Content)         // decoded payload
	fmt.Println(m.Version())       // symbol version, 1-40
}

Decode accepts anything readable and decodable by Go's image package with PNG and JPEG registered (this package imports both for side effects).

If you already hold an image.Image — a decoded frame, a cropped region, a canvas — skip the file handling:

m, err := qrcode.DecodeImg(img)
if err != nil {
	log.Fatal(err)
}
fmt.Println(m.Content)

For other formats (GIF, WebP, BMP, …), decode the image yourself and call DecodeImg.

Run the bundled example
cd example
go run .

The example reads qrcode15.jpeg from its own directory, so run it from example/.

API

Symbol Description
qrcode.Decode(r io.Reader) (*Matrix, error) Decode a QR code from an encoded image (PNG/JPEG).
qrcode.DecodeImg(img image.Image) (*Matrix, error) Decode a QR code from an already-decoded image.
(*Matrix).Content Decoded payload as a string.
(*Matrix).Version() Symbol version (1–40), derived from the sampled grid.
(*Matrix).FormatInfo() Error-correction level and mask pattern; level values follow ISO/IEC 18004 (0 = M, 1 = L, 2 = H, 3 = Q).
(*Matrix).Points, (*Matrix).Size Sampled module grid and its dimensions, useful for debugging or re-rendering.
qrcode.QRReconstruct(data, ecc []byte) ([]byte, error) Correct data codewords with the supplied ECC codewords.

Lower-level building blocks (NewPositionDetectionPattern, MaskFunc, ParseBlock, Bits2Bytes, …) are exported as well; they are mainly useful when experimenting with the detection pipeline and are not covered by compatibility guarantees.

How it works

  1. Binarize — the image is converted to grayscale and thresholded with Otsu's method.
  2. Locate finders — two complementary strategies:
    • Connected components: a 3×3 solid core inside a 7×7 hollow ring, with an area-ratio sanity check.
    • Scanline: run-length scans along rows and columns matching the 1:1:3:1:1 ratio, independent of connectedness and global polarity.
  3. Sample modules — three finder centers define an affine frame (handles rotation); when an alignment pattern is found, four points define a homography (handles perspective).
  4. Read and correct — format information is BCH-validated (both copies), the mask is removed, codewords are read in the standard zig-zag order, deinterleaved per block, and Reed–Solomon corrected.
  5. Decode content — mode indicators select the numeric, alphanumeric, byte, or Kanji decoder.

For tough inputs the detector walks a fallback ladder and stops at the first success: downscaled grid → downscaled + eroded → full resolution → full resolution + eroded → scanline. Erosion only affects detection; sampled modules always come from grayscale pixels, so it never damages the payload.

Supported input and limitations

  • Decoder only — this package does not generate QR codes.
  • One symbol per image — multi-code scenes and structured-append sequences are not reassembled.
  • No ECI handling — byte-mode payloads are returned verbatim. Bytes are converted to string as-is, so interpreting non-UTF-8 text (or binary data) is up to the caller.
  • Kanji mode assumes Shift JIS, as specified by the standard.
  • Dot-style codes under strong perspective — the scanline fallback samples with three finder patterns only (no alignment pattern), so very high-version art codes that are also heavily keystoned may fail. Regular solid-module codes use the full homography path.

Performance

Detection runs on a downscaled binary grid when the long edge exceeds ~1000 px (integer factor, capped at 4), then modules are sampled from the full-resolution grayscale image. This keeps large photos fast without sacrificing accuracy.

End-to-end timings are dominated by image decoding (PNG inflate / JPEG), not by QR logic. Two benchmarks separate the layers:

go test -run '^$' -bench 'BenchmarkDecodeImg' -benchmem  # library only, image pre-decoded
go test -run '^$' -bench 'BenchmarkDecode$' -benchmem    # full pipeline

Testing

go test ./...

example/ doubles as the regression corpus and covers:

  • plain screenshots and high-contrast renders,
  • rotated and perspective-distorted photos,
  • a screen capture with logo noise and glare (qrcode23.png),
  • an inverted, dot-style art code (qrcode12.png),
  • all four data modes, including Chinese text and Kanji.

Expected content for each image lives in decodeCases in qrcode_test.go, which is shared by the tests and BenchmarkDecode. To add a case: drop the image into example/, add its expected payload to decodeCases, and run go test ./....

Reference documents

doc/ contains the material this implementation was written against:

  • qr_standard.pdf — ISO/IEC 18004, the QR code specification.
  • bch.pdf — BCH coding, used by the format-information checks.
  • 基于边缘增强的二维码区域快速检测定位算法.pdf — edge-enhanced QR region detection.

Contributing

Issues and pull requests are welcome. Before submitting:

gofmt -l .
go vet ./...
go test ./...

Keep new test images in example/ with their expected payload in decodeCases, and note in the PR which detection path your change affects.

License

GNU General Public License v3.0.


中文速览

纯 Go 实现的 二维码解码库,输入图片,输出内容。不依赖 CGO,也不需要外部可执行文件。

安装
go get github.com/tuotoo/qrcode

需要 Go 1.27 及以上版本。

用法
f, err := os.Open("qrcode1.png")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

m, err := qrcode.Decode(f)
if err != nil {
	log.Fatal(err)
}
fmt.Println(m.Content)   // 解码内容
fmt.Println(m.Version()) // 版本号 1-40

已经拿到 image.Image 时(视频帧、裁剪区域、画布)直接调用 qrcode.DecodeImg(img); GIF/WebP/BMP 等格式请自行解码后再走 DecodeImg。

能力
  • 支持版本 1–40、纠错等级 L/M/Q/H;
  • 支持数字、字母数字、8-bit 字节、汉字(Shift JIS 转 UTF-8)四种编码模式;
  • 支持旋转(三点仿射采样)与透视畸变(对齐图案 + 单应矩阵);
  • 大津法自适应二值化,适应光照不均;
  • Reed–Solomon 纠错;
  • 支持反色、圆点式艺术二维码(扫描线 1:1:3:1:1 回退路径);
  • 大图先下采样定位、再全分辨率采样,兼顾速度与精度。

检测失败时会依次回退:下采样 → 下采样+腐蚀 → 全分辨率 → 全分辨率+腐蚀 → 扫描线法。

限制
  • 只解码,不生成二维码;
  • 一张图只处理一个二维码,不支持多码检测与 structured append 拼接;
  • 不处理 ECI,字节模式内容按原始字节返回,非 UTF-8 文本需调用方自行转码;
  • 汉字模式按标准假定为 Shift JIS;
  • 扫描线回退只用三个定位符做仿射采样,高版本 + 强透视的艺术码可能失败(常规实心码走单应矩阵路径)。
测试
go test ./...
go test -run '^$' -bench 'BenchmarkDecodeImg' -benchmem   # 库自身耗时(预解码图像)
go test -run '^$' -bench 'BenchmarkDecode$' -benchmem     # 端到端耗时

example/ 目录同时是回归测试集,预期内容见 qrcode_test.go 的 decodeCases。

Documentation

Overview

Package qrcode implements a QR code decoder.

Index

Constants

This section is empty.

Variables

View Source
var (
	// AlignmentPatternCenter lists the module coordinates of alignment pattern
	// centers for each QR version.
	AlignmentPatternCenter = [][]int{
		{},
		{},
		{6, 18},
		{6, 22},
		{6, 26},
		{6, 30},
		{6, 34},
		{6, 22, 38},
		{6, 24, 42},
		{6, 26, 46},
		{6, 28, 50},
		{6, 30, 54},
		{6, 32, 58},
		{6, 34, 62},
		{6, 26, 46, 66},
		{6, 26, 48, 70},
		{6, 26, 50, 74},
		{6, 30, 54, 78},
		{6, 30, 56, 82},
		{6, 30, 58, 86},
		{6, 34, 62, 90},
		{6, 28, 50, 72, 94},
		{6, 26, 50, 74, 98},
		{6, 30, 54, 78, 102},
		{6, 28, 54, 80, 106},
		{6, 32, 58, 84, 110},
		{6, 30, 58, 86, 114},
		{6, 34, 62, 90, 118},
		{6, 26, 50, 74, 98, 122},
		{6, 30, 54, 78, 102, 126},
		{6, 26, 52, 78, 104, 130},
		{6, 30, 56, 82, 108, 134},
		{6, 34, 60, 86, 112, 138},
		{6, 30, 58, 86, 114, 142},
		{6, 34, 62, 90, 118, 146},
		{6, 30, 54, 78, 102, 126, 150},
		{6, 24, 50, 76, 102, 128, 154},
		{6, 28, 54, 80, 106, 132, 158},
		{6, 32, 58, 84, 110, 136, 162},
		{6, 26, 54, 82, 110, 138, 166},
		{6, 30, 58, 86, 114, 142, 170},
	}
	// Versions lists every QR code version at every error correction level.
	Versions = []QRcodeVersion{}/* 160 elements not displayed */

)
View Source
var AlphanumericDecoderChar = []string{
	"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
	"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
	"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
	"U", "V", "W", "X", "Y", "Z", "SP", "$", "%", "*",
	"+", "-", ".", "/", ":"}

AlphanumericDecoderChar is the QR alphanumeric character set, in value order.

Functions

func Bit2Byte

func Bit2Byte(bits []bool) byte

Bit2Byte interprets a bit slice as a byte.

func Bit2Int

func Bit2Int(bits []bool) int

Bit2Int interprets a bit slice as a big-endian unsigned integer.

func Bits2Bytes

func Bits2Bytes(dataCode []bool, version int) ([]byte, error)

Bits2Bytes decodes the data bits (mode + payload) into the final content.

func Bool2Byte

func Bool2Byte(dataCode []bool) []byte

Bool2Byte converts a bit slice into a byte slice, dropping any trailing bits.

func Byte2Bool

func Byte2Bool(bl []byte) []bool

Byte2Bool converts a byte slice into a bit slice (most significant bit first).

func GetData

func GetData(unmaskMatrix, dataArea *Matrix) []bool

GetData reads the data bits from the unmasked matrix in the QR zigzag order.

func GetDataEncoder

func GetDataEncoder(version int) (*dataEncoder, error)

GetDataEncoder returns the data encoder for the given QR version.

func Hollow

func Hollow(group *PosGroup) bool

Hollow reports whether a PosGroup contains holes or internal gaps. It compares the total pixel count against the sum of per-row bounding spans: a row whose black pixels are not contiguous makes its span wider than its pixel count, leaving a non-zero remainder. Rows are tracked by their min/max x. For the common case of a compact group we use plain arrays indexed by row offset (no hashing, no allocation churn); very tall groups fall back to a map.

func IsPositionDetectionPattern

func IsPositionDetectionPattern(solidGroup, hollowGroup *PosGroup) bool

IsPositionDetectionPattern reports whether a solid group lies inside a hollow group, forming a QR finder pattern.

func IsVertical

func IsVertical(kf, kl *K) (offset float64)

IsVertical returns the angular offset between two edges and a right angle.

func MaskFunc

func MaskFunc(code int) func(x, y int) bool

MaskFunc returns the mask function for the given QR mask pattern code.

func ParseBlock

func ParseBlock(m *Matrix, data []bool) ([]bool, error)

ParseBlock splits the data bits into blocks, applies Reed-Solomon error correction, and reassembles the corrected data bits.

func QRReconstruct

func QRReconstruct(data, ecc []byte) ([]byte, error)

QRReconstruct corrects errors in data using the Reed-Solomon ecc codewords.

func Radian

func Radian(k *K)

Radian computes the angle of the edge k in radians.

func Rectangle

func Rectangle(group []Pos) (minX, maxX, minY, maxY int)

Rectangle returns the axis-aligned bounding box of a point group.

func SplitGroup

func SplitGroup(poss *[][]bool, centerX, centerY int, around *[]Pos)

SplitGroup performs an 8-neighbor flood fill starting at (centerX, centerY), removing visited points from poss and appending them to around.

Types

type AlphanumericDecoder

type AlphanumericDecoder struct {
	// contains filtered or unexported fields
}

AlphanumericDecoder decodes QR alphanumeric mode data.

func (*AlphanumericDecoder) Decode

func (d *AlphanumericDecoder) Decode(data []bool) ([]byte, error)

type Block

type Block struct {
	NumBlocks int

	// Total codewords (NumCodewords == numErrorCodewords+NumDataCodewords).
	NumCodewords int

	// Number of data codewords.
	NumDataCodewords int
}

type EightBitDecoder

type EightBitDecoder struct {
	// contains filtered or unexported fields
}

EightBitDecoder decodes QR 8-bit byte mode data.

func (*EightBitDecoder) Decode

func (d *EightBitDecoder) Decode(data []bool) ([]byte, error)

type FormatInfo

type FormatInfo struct {
	ErrorCorrectionLevel, Mask int
}

FormatInfo holds the error correction level and mask of a QR code.

type K

type K struct {
	FirstPosGroup *PosGroup
	LastPosGroup  *PosGroup
	K             float64
}

K is an edge connecting two finder patterns, used to compute their angle.

type KanjiDecoder

type KanjiDecoder struct {
	// contains filtered or unexported fields
}

KanjiDecoder decodes QR Kanji mode data (Shift JIS encoded).

func (*KanjiDecoder) Decode

func (d *KanjiDecoder) Decode(data []bool) ([]byte, error)

type Matrix

type Matrix struct {
	OrgImage  image.Image
	OrgSize   image.Rectangle
	OrgPoints [][]bool
	Points    [][]bool
	Size      image.Rectangle
	Data      []bool
	Content   string
	// contains filtered or unexported fields
}

Matrix is the decoded QR code. It holds the original image, its binarized form, the sampled module grid, and the decoded content.

func Decode

func Decode(fi io.Reader) (*Matrix, error)

Decode decodes a QR code from an io.Reader and returns its content.

func DecodeImg

func DecodeImg(img image.Image) (*Matrix, error)

DecodeImg decodes a QR code from an image, returning the sampled matrix with its content populated.

func (*Matrix) AtOrgPoints

func (mx *Matrix) AtOrgPoints(x, y int) bool

func (*Matrix) AtPoints

func (mx *Matrix) AtPoints(x, y int) bool

func (*Matrix) Binarization

func (mx *Matrix) Binarization(pic *image.Gray) uint8

Binarization 使用大津法(Otsu)自动计算全局阈值,避免固定阈值对光照变化敏感。

func (*Matrix) DataArea

func (mx *Matrix) DataArea() *Matrix

func (*Matrix) FormatInfo

func (mx *Matrix) FormatInfo() (*FormatInfo, error)

func (*Matrix) GetBin

func (mx *Matrix) GetBin(poss []Pos) int

func (*Matrix) ReadImage

func (mx *Matrix) ReadImage()

func (*Matrix) SplitGroups

func (mx *Matrix) SplitGroups() [][]Pos

SplitGroups splits the matrix's binary grid into connected components.

func (*Matrix) Version

func (mx *Matrix) Version() int

type ModeCharDecoder

type ModeCharDecoder interface {
	Decode(b []bool) ([]byte, error)
}

type NumericDecoder

type NumericDecoder struct {
	// contains filtered or unexported fields
}

NumericDecoder decodes QR numeric mode data.

func (*NumericDecoder) Decode

func (d *NumericDecoder) Decode(data []bool) ([]byte, error)

type Pos

type Pos struct {
	X int
	Y int
}

Pos is a 2D coordinate.

func CenterPoint

func CenterPoint(group []Pos) Pos

CenterPoint returns the mean coordinate of a point group.

type PosGroup

type PosGroup struct {
	Group  []Pos
	Min    Pos
	Max    Pos
	Center Pos
	Hollow bool
}

PosGroup is a connected group of pixels (a connected component) together with its geometric properties.

func PossListToGroup

func PossListToGroup(groups []*PosGroup) *PosGroup

PossListToGroup merges multiple PosGroups into a single one.

func PossToGroup

func PossToGroup(group []Pos) *PosGroup

PossToGroup builds a PosGroup from a slice of points, computing its center, bounding box, and hollowness.

type PositionDetectionPatterns

type PositionDetectionPatterns struct {
	TopLeft *PosGroup
	Right   *PosGroup
	Bottom  *PosGroup
}

PositionDetectionPatterns holds the three finder patterns of a QR code: top-left, top-right, and bottom-left.

func NewPositionDetectionPattern

func NewPositionDetectionPattern(PDPs [][]*PosGroup) (*PositionDetectionPatterns, error)

NewPositionDetectionPattern identifies the three finder patterns from the candidate solid/hollow pairs and determines their roles (top-left, top-right, bottom-left).

type QRcodeVersion

type QRcodeVersion struct {
	// Version number (1-40 inclusive).
	Version int

	// Error recovery Level.
	Level RecoveryLevel

	DataEncoderType dataEncoderType

	// Encoded data can be split into multiple blocks. Each Block contains data
	// and error recovery bytes.
	//
	// Larger QR Codes contain more blocks.
	Block []Block

	// Number of bits required to pad the combined data & error correction bit
	// stream up to the symbol's full capacity.
	NumRemainderBits int
}

QRcodeVersion describes the data length and encoding order of a single QR Code Version. There are 40 versions numbers x 4 recovery levels == 160 possible QRcodeVersion structures.

type RecoveryLevel

type RecoveryLevel int

Error detection/recovery capacity.

There are several levels of error detection/recovery capacity. Higher levels of error recovery are able to correct more errors, with the trade-off of increased symbol size.

const (
	// Level M: 15% error recovery. Good default choice. 0b00
	Medium RecoveryLevel = iota
	// Level L: 7% error recovery. 0b01
	Low
	// Level H: 30% error recovery.0b10
	Highest
	// Level Q: 25% error recovery.0b11
	High
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址