qrcode

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2026 License: MIT Imports: 26 Imported by: 0

README

qrcode

QR code generation (with optional logo overlay and styled modules), decoding, and anti-counterfeiting signing/encryption.

Features

  • Generation: Generate, GeneratePNG, Save with configurable error-correction level
  • Logo overlay: composite a logo onto the QR center with a safe zone
  • Fancy/styled: custom module shapes (circle, rounded, liquid, stripes, diamond), gradients, transparent background, halftone QR
  • Templates: named style presets (simple / classic / creative / custom) via GenerateFromTemplate
  • Decoding: Decode, DecodeFile, DecodeBytes via ZXing (gozxing)
  • Anti-counterfeiting: Sign/Verify (HMAC), Encrypt/Decrypt (AES-GCM), Secure/Unseal (encrypt + sign)

Key types

  • ErrorCorrectionLevel — ECLLow, ECLMedium, ECLQuartile, ECLHigh
  • ModuleShape — styled module shapes for fancy QR codes
  • Template / TemplateCategory — gallery presets for fancy QR

Quick start

import "github.com/LingByte/ling-base/common/qrcode"

pngBytes, _ := qrcode.GeneratePNG("https://example.com", qrcode.ECLMedium, 256)
_ = qrcode.Save("https://example.com", "qr.png", qrcode.ECLHigh, 400)

// Named style template (e.g. simple-dots, classic-ocean, creative-neon).
fancy, _ := qrcode.GenerateFromTemplate("https://example.com", "classic-ocean")
_ = fancy

// List gallery tabs: simple | classic | creative | custom
for _, t := range qrcode.ListTemplates(qrcode.CategorySimple) {
    _ = t.ID // "simple-dots", ...
}

text, _ := qrcode.DecodeFile("qr.png")

// Anti-counterfeit: sign then verify.
token, _ := qrcode.Sign("product-id:12345", secretKey)
payload, err := qrcode.Verify(token, secretKey, 0)

Template scope

Built-in templates cover parametric styling (module shape, finder shape, solid/gradient colors) — the same class as product UIs under 黑白简约 / 经典绚丽 / 创意样式.

AI artistic QR (ControlNet / Stable Diffusion scenes that paint the code into photos) is out of scope for this package: that needs an external image model. You can still feed a stylized bitmap into FancyOptions.Halftone or overlay a logo after generation.

Documentation

Overview

Package qrcode provides QR code generation (with optional logo overlay) and decoding. Generation uses github.com/boombuler/barcode; decoding uses github.com/makiuchi-d/gozxing (a Go port of ZXing). Logo overlay uses the local imageutil package for compositing.

Index

Constants

View Source
const TokenPrefix = "LB1."

TokenPrefix is prepended to every signed/encrypted QR token so that verifiers can quickly distinguish a secure token from plain text.

Variables

This section is empty.

Functions

func ClearCustomTemplates added in v0.2.0

func ClearCustomTemplates()

ClearCustomTemplates removes all user-registered templates.

func Decode

func Decode(img image.Image) (string, error)

Decode reads a QR code from an image and returns the decoded text. If no QR code is found, an error is returned.

func DecodeBytes

func DecodeBytes(data []byte) (string, error)

DecodeBytes decodes a QR code from raw image bytes (PNG, JPEG, etc.).

func DecodeFile

func DecodeFile(path string) (string, error)

DecodeFile reads an image file and decodes the QR code from it.

func Decrypt

func Decrypt(token string, key []byte) (string, error)

Decrypt decodes a token produced by Encrypt and returns the original plaintext payload.

func Encrypt

func Encrypt(payload string, key []byte) (string, error)

Encrypt produces a base64url-encoded token containing the AES-GCM encrypted payload. The token can be embedded in a QR code. Only someone with the same key can decrypt and read the content. The key must be 16, 24, or 32 bytes (AES-128/192/256).

func Generate

func Generate(text string, level ErrorCorrectionLevel, size int) (image.Image, error)

Generate creates a QR code image from the given text. The returned image is scaled to size×size pixels (nearest-neighbor). If size is 0, the unscaled 1-module-per-pixel barcode is returned.

func GenerateFancy

func GenerateFancy(text string, level ErrorCorrectionLevel, opts FancyOptions) ([]byte, error)

GenerateFancy creates a styled QR code and returns it as a PNG-encoded byte slice.

func GenerateFancyImage

func GenerateFancyImage(text string, level ErrorCorrectionLevel, opts FancyOptions) (image.Image, error)

GenerateFancyImage creates a styled QR code and returns it as an image.Image (decoded from the internally-generated PNG).

func GenerateFromTemplate added in v0.2.0

func GenerateFromTemplate(text, templateID string, override ...TemplateOverride) ([]byte, error)

GenerateFromTemplate applies a named template and returns PNG bytes.

func GeneratePNG

func GeneratePNG(text string, level ErrorCorrectionLevel, size int) ([]byte, error)

GeneratePNG creates a QR code and encodes it as PNG bytes.

func GenerateSecure

func GenerateSecure(payload string, encryptKey, signKey []byte, level ErrorCorrectionLevel, size int) (image.Image, error)

GenerateSecure generates a QR code whose content is an encrypted + signed token (produced by Secure).

func GenerateSigned

func GenerateSigned(payload string, secret []byte, level ErrorCorrectionLevel, size int) (image.Image, error)

GenerateSigned generates a QR code whose content is a signed token (produced by Sign). This is a convenience for anti-counterfeit labels.

func GenerateWithLogo(text string, level ErrorCorrectionLevel, size int, logo image.Image, logoSize int) (image.Image, error)

GenerateWithLogo creates a QR code with a logo image composited at the center. The logo is scaled to logoSize×logoSize pixels (if logoSize > 0, otherwise it defaults to ~20% of the QR size). A white background plate is drawn behind the logo for readability. The QR code should use at least ECLQuartile or ECLHigh when embedding a logo to maintain scannability.

func GenerateWithLogoFile

func GenerateWithLogoFile(text string, level ErrorCorrectionLevel, size int, logoPath string, logoSize int) (image.Image, error)

GenerateWithLogoFile is like GenerateWithLogo but loads the logo from a file path.

func GenerateWithLogoPNG

func GenerateWithLogoPNG(text string, level ErrorCorrectionLevel, size int, logo image.Image, logoSize int) ([]byte, error)

GenerateWithLogoPNG creates a QR code with a logo and encodes it as PNG.

func IsSecureToken

func IsSecureToken(s string) bool

IsSecureToken returns true if the string looks like a token produced by Sign, Encrypt, or Secure (i.e. it has the TokenPrefix).

func RegisterTemplate added in v0.2.0

func RegisterTemplate(t Template) error

RegisterTemplate stores a custom template. Built-in IDs cannot be overwritten. Empty Category defaults to CategoryCustom.

func Save

func Save(text, path string, level ErrorCorrectionLevel, size int) error

Save generates a QR code and writes it to a PNG file.

func SaveFancy

func SaveFancy(text, path string, level ErrorCorrectionLevel, opts FancyOptions) error

SaveFancy creates a styled QR code and writes it to a PNG file.

func SaveFromTemplate added in v0.2.0

func SaveFromTemplate(text, path, templateID string, override ...TemplateOverride) error

SaveFromTemplate generates a styled QR from a template and writes a PNG file.

func SaveWithLogo(text, path string, level ErrorCorrectionLevel, size int, logo image.Image, logoSize int) error

SaveWithLogo generates a QR code with a logo and writes it to a PNG file.

func SaveWithLogoFile

func SaveWithLogoFile(text, outputPath string, level ErrorCorrectionLevel, size int, logoPath string, logoSize int) error

SaveWithLogoFile generates a QR code with a logo loaded from a file and writes the result to a PNG file.

func Secure

func Secure(payload string, encryptKey, signKey []byte) (string, error)

Secure produces a token that first AES-GCM encrypts the payload (confidentiality) and then HMAC-signs the ciphertext (integrity). This is the recommended approach for anti-counterfeit labels where both secrecy and tamper detection are required.

The encryptKey must be 16/24/32 bytes; the signKey must be non-empty.

func Sign

func Sign(payload string, secret []byte) (string, error)

Sign produces a base64url-encoded token containing the payload and its HMAC-SHA256 signature. The token can be embedded in a QR code. Anyone with the secret key can later verify the payload's integrity.

func UnregisterTemplate added in v0.2.0

func UnregisterTemplate(id string)

UnregisterTemplate removes a previously registered custom template.

func Unseal

func Unseal(token string, encryptKey, signKey []byte, maxAge time.Duration) (string, error)

Unseal verifies and decrypts a token produced by Secure, returning the original plaintext payload. Returns an error if the signature is invalid or decryption fails.

func Verify

func Verify(token string, secret []byte, maxAge time.Duration) (string, error)

Verify checks a token produced by Sign and returns the original payload if the signature is valid. Returns an error if the token is malformed, the signature does not match, or (if maxAge > 0) the token is older than maxAge.

Types

type ColorStop

type ColorStop struct {
	Color color.Color
	T     float64
}

ColorStop represents a single color at position T (0.0 to 1.0).

type ErrorCorrectionLevel

type ErrorCorrectionLevel int

ErrorCorrectionLevel controls the redundancy of the QR code. Higher levels allow more damage (or a larger logo overlay) while remaining readable.

const (
	// ECLLow recovers ~7% of data. Smallest QR, least tolerance.
	ECLLow ErrorCorrectionLevel = iota
	// ECLMedium recovers ~15%. Good general-purpose default.
	ECLMedium
	// ECLQuartile recovers ~25%. Recommended when embedding a logo.
	ECLQuartile
	// ECLHigh recovers ~30%. Maximum tolerance; largest QR.
	ECLHigh
)

type FancyOptions

type FancyOptions struct {
	// Module shape for data blocks. Default: ShapeRectangle.
	Module ModuleShape
	// Finder (corner) shape. Default: FinderSquare.
	Finder FinderShape

	// Foreground color (modules). If FgGradient is set, this is ignored.
	// Default: black.
	FgColor color.Color
	// Background color. If BgTransparent is true, this is ignored.
	// Default: white.
	BgColor color.Color
	// BgTransparent makes the background transparent (PNG only).
	BgTransparent bool

	// FgGradient applies a linear gradient to the foreground modules.
	// If set, FgColor is ignored.
	FgGradient *LinearGradient

	Logo image.Image
	// LogoSizeMultiplier controls logo size relative to QR width.
	// Default is 4 (logo = 1/4 of QR). Use 5 for a smaller logo.
	LogoSizeMultiplier int
	// LogoSafeZone adds a white safe zone around the logo.
	LogoSafeZone bool

	// Halftone image — modules are rendered from this image, creating
	// an artistic QR. Optional.
	Halftone image.Image

	// ModuleWidth is the pixel width of each QR module. Default: 21.
	ModuleWidth uint8
	// BorderWidth is the quiet-zone width in pixels on all 4 sides.
	// Default: 0 (no extra border).
	BorderWidth int
}

FancyOptions controls the visual style of a fancy QR code. All fields are optional; zero values produce sensible defaults.

func FancyCirclePreset

func FancyCirclePreset(fg, bg color.Color) FancyOptions

FancyCirclePreset returns options for a clean circle-module QR with the given foreground and background colors.

func FancyGradientPreset

func FancyGradientPreset(gradient *LinearGradient) FancyOptions

FancyGradientPreset returns options for a circle-module QR with a linear gradient foreground.

func FancyHalftonePreset

func FancyHalftonePreset(src image.Image, fg color.Color) FancyOptions

FancyHalftonePreset returns options for a halftone QR where modules are rendered from the given source image.

func FancyLogoPreset

func FancyLogoPreset(logo image.Image) FancyOptions

FancyLogoPreset returns options for a QR with a logo at the center, rounded finder patterns, and circle modules.

type FinderShape

type FinderShape int

FinderShape describes the visual shape of the three corner finder patterns.

const (
	// FinderRounded renders rounded finder patterns.
	FinderRounded FinderShape = iota
	// FinderSquare renders square finder patterns (default).
	FinderSquare
)

type LinearGradient

type LinearGradient struct {
	Angle float64     // degrees, 0 = horizontal left→right
	Stops []ColorStop // color stops along the gradient
}

LinearGradient is a linear color gradient for QR foreground modules.

func NewLinearGradient

func NewLinearGradient(angle float64, stops ...ColorStop) *LinearGradient

NewLinearGradient creates a linear gradient with the given angle and color stops.

type ModuleShape

type ModuleShape int

ModuleShape describes the visual shape of each QR module (data bit).

const (
	// ShapeRectangle uses the default square modules.
	ShapeRectangle ModuleShape = iota
	// ShapeCircle renders each module as a filled circle.
	ShapeCircle
	// ShapeRounded renders each module as a rounded rectangle.
	ShapeRounded
	// ShapeLiquid renders connected modules as a single liquid blob.
	ShapeLiquid
	// ShapeHStripe renders each module as horizontal stripes.
	ShapeHStripe
	// ShapeVStripe renders each module as vertical stripes.
	ShapeVStripe
	// ShapeDiamond renders each module as a 45° rotated square.
	ShapeDiamond
)

type Template added in v0.2.0

type Template struct {
	// ID is a stable machine key (e.g. "simple-dots").
	ID string
	// Name is a human-readable label (often Chinese, matching UI copy).
	Name string
	// Category selects which gallery tab this template belongs to.
	Category TemplateCategory
	// Options are the visual parameters applied when generating.
	Options FancyOptions
	// Level is the default error-correction level. Zero means ECLHigh
	// (recommended for styled / logo QR codes).
	Level ErrorCorrectionLevel
}

Template is a named FancyOptions preset that can be listed, selected, and applied in one call (GenerateFromTemplate).

func BuiltinTemplates added in v0.2.0

func BuiltinTemplates() []Template

BuiltinTemplates returns a copy of all built-in style templates.

func GetTemplate added in v0.2.0

func GetTemplate(id string) (Template, bool)

GetTemplate looks up a built-in or custom template by ID.

func ListTemplates added in v0.2.0

func ListTemplates(category TemplateCategory) []Template

ListTemplates returns built-ins plus custom templates. Pass an empty category to list everything.

type TemplateCategory added in v0.2.0

type TemplateCategory string

TemplateCategory groups fancy QR style presets (mirrors product UI tabs).

const (
	// CategorySimple is 黑白简约 — monochrome module/finder styles.
	CategorySimple TemplateCategory = "simple"
	// CategoryClassic is 经典绚丽 — colorful gradients and vivid solids.
	CategoryClassic TemplateCategory = "classic"
	// CategoryCreative is 创意样式 — bolder shapes and multi-stop gradients.
	CategoryCreative TemplateCategory = "creative"
	// CategoryCustom is 我的模板 — user-registered presets via RegisterTemplate.
	CategoryCustom TemplateCategory = "custom"
)

type TemplateOverride added in v0.2.0

type TemplateOverride struct {
	LogoSizeMultiplier int
	LogoSafeZone       bool
	Halftone           image.Image
	ModuleWidth        uint8
	BorderWidth        int
	FgColor            color.Color
	BgColor            color.Color
	FgGradient         *LinearGradient
	BgTransparent      bool
}

TemplateOverride patches a template at generate time (logo, size, etc.) without mutating the registered preset.

Jump to

Keyboard shortcuts

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