qrgode

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: MIT Imports: 19 Imported by: 0

README

qr-gode

Go Reference Go Report Card CI Coverage Status

qr-gode banner

A feature-rich QR code generator library for Go with extensive customization options.

Showcase

Classic square Circle modules Rounded with linear gradient Dot with radial gradient
Classic Circle Rounded · linear gradient Dot · radial gradient
Heart modules Star with gradient Diamond modules Dark mode
Heart Star · gradient Diamond Dark mode
Logo classic Logo in overlay mode
Logo · classic Logo · overlay mode

Reproduce these with go run ./cmd/gen-showcase.

Features

  • Multiple module shapes (square, circle, rounded, diamond, dot, star, heart)
  • Solid colors and gradients (linear & radial)
  • Custom images for finder patterns, alignment patterns, and modules
  • Logo support with automatic sizing, configurable padding, and exclude/overlay placement modes
  • SVG and PNG output — every styling feature works in both formats
  • Configurable error correction levels

Installation

go get github.com/ahmedtahas/qr-gode

Quick Start

CLI Usage
# Basic QR code
qr-gode "https://example.com"

# Custom styling
qr-gode -shape circle -fg "#3498db" "Hello World"

# Gradient colors
qr-gode -gradient "#ff6b6b,#4ecdc4" -shape rounded "Gradient QR"

# With a logo
qr-gode -logo logo.png "https://example.com"

# Custom images for patterns
qr-gode -finder-img finder.png -module-img dot.png "Custom QR"
CLI Options
Flag Description Default
-o Output file path (.svg or .png) qrcode.svg
-size Output size in pixels 512
-shape Module shape square
-fg Foreground color (hex) #000000
-bg Background color (hex) #FFFFFF
-gradient Gradient colors (comma-separated) -
-gradient-angle Gradient angle in degrees 45
-radial Use radial gradient false
-ecl Error correction level (L, M, Q, H) M
-logo Logo image path (PNG/JPG/SVG) -
-logo-width Logo width in pixels (0 = auto) 0
-logo-height Logo height in pixels (0 = auto) 0
-finder-img Custom finder pattern image -
-align-img Custom alignment pattern image -
-module-img Custom module image -

Library Usage

The fluent builder API is the simplest way to generate QR codes:

package main

import (
    "os"

    qrgode "github.com/ahmedtahas/qr-gode"
)

func main() {
    // Simple QR code
    svg, err := qrgode.New("https://example.com").SVG()
    if err != nil {
        panic(err)
    }
    os.WriteFile("qr.svg", svg, 0644)
}
Styling Options
// Custom colors and shape
svg, _ := qrgode.New("Hello World").
    Size(512).
    Shape(qrgode.ShapeCircle).
    Foreground("#3498db").
    Background("#ffffff").
    SVG()

// Linear gradient
svg, _ := qrgode.New("Gradient QR").
    Shape(qrgode.ShapeRounded).
    LinearGradient(45, "#ff6b6b", "#4ecdc4").
    SVG()

// Radial gradient
svg, _ := qrgode.New("Radial QR").
    Shape(qrgode.ShapeDot).
    RadialGradient(0.5, 0.5, "#ff6b6b", "#4ecdc4", "#45b7d1").
    SVG()
// Auto-sized logo from file (15-30% of QR size, preserves aspect ratio)
svg, _ := qrgode.New("https://example.com").
    Logo("logo.png").
    SVG()

// Logo from in-memory image
svg, _ := qrgode.New("https://example.com").
    LogoImage(myImage). // image.Image
    SVG()

// Custom logo dimensions
svg, _ := qrgode.New("https://example.com").
    Logo("logo.png").
    LogoWidth(100).
    SVG()

// Transparent logo background
svg, _ := qrgode.New("https://example.com").
    Logo("logo.png").
    LogoBackground("transparent").
    SVG()
Custom Pattern Images
// Use custom images for QR elements
svg, _ := qrgode.New("Custom QR").
    FinderImage("finder.png").
    AlignmentImage("alignment.png").
    ModuleImage("module.png").
    SVG()
Error Correction
// Higher error correction for logos or damaged codes
svg, _ := qrgode.New("https://example.com").
    ErrorCorrection(qrgode.LevelH). // 30% recovery
    Logo("logo.png").
    SVG()
Functional Options API

Alternative API using functional options:

svg, err := qrgode.GenerateWithOptions("https://example.com",
    qrgode.WithSize(512),
    qrgode.WithModuleShape("circle"),
    qrgode.WithLogo("logo.png"),
)
Direct Config API

For full control, use the Config struct directly:

cfg := qrgode.DefaultConfig()
cfg.Size = 512
cfg.Modules.Shape = "circle"
cfg.Modules.Color = qrgode.NewLinearGradientColor(45, []string{"#ff6b6b", "#4ecdc4"})
cfg.Logo = &qrgode.LogoConfig{
    Path: "logo.png",
}

svg, err := qrgode.Generate("https://example.com", cfg)
Simple Generate Functions

For quick generation without configuration:

// Generate to bytes
svg, err := qrgode.Generate("https://example.com", nil)

// Generate directly to file
err := qrgode.GenerateToFile("https://example.com", nil, "qr.svg")

Available Shapes

Use the typed Shape constants for type safety:

Constant Value Description
ShapeSquare "square" Standard square modules (default)
ShapeCircle "circle" Circular modules
ShapeRounded "rounded" Rounded square modules
ShapeDiamond "diamond" Diamond/rotated square modules
ShapeDot "dot" Small centered dots
ShapeStar "star" Star-shaped modules
ShapeHeart "heart" Heart-shaped modules

Error Correction Levels

Constant Recovery Capacity Use Case
LevelL ~7% Maximum data density
LevelM ~15% Default, balanced
LevelQ ~25% Better recovery
LevelH ~30% Best recovery, use with logos

When adding a logo, consider using LevelQ or LevelH to ensure the QR code remains scannable.

Scannability check

For logo+ECL combinations that are likely to break scanning, call ScannabilityWarnings() and surface the results however you like:

qr := qrgode.New("https://example.com").
    Logo("logo.png").
    ErrorCorrection(qrgode.LevelM)

for _, msg := range qr.ScannabilityWarnings() {
    log.Println("qrgode:", msg)
}

The check is heuristic — print quality, contrast, and scanner camera also affect real-world scannability — but it catches the common mistake of pairing a large logo with a low error-correction level.

Custom Images

Finder Pattern Image

The finder pattern image should be a 7x7 module pattern:

  • Outer ring (dark)
  • White gap
  • Inner 3x3 square (dark)
Alignment Pattern Image

The alignment pattern image should be a 5x5 module pattern:

  • Outer ring (dark)
  • White gap
  • Center dot (dark)
Module Image

Any square image that represents a single dark module.

Logo Handling

  • Auto-sizing: By default, logos are scaled to fit within 15-30% of the QR code size
  • Aspect ratio: Always preserved - logos are never stretched
  • In-memory support: Use LogoImage() to pass an image.Image directly
  • SVG logos: Treated as 1:1 aspect ratio, scale perfectly at any size
  • Background: White rounded rectangle by default, can be set to transparent
Placement: exclude vs. overlay
// Exclude (default): modules under the logo are skipped — cleaner look,
// the error-correction budget absorbs the loss.
qrgode.New(data).Logo("logo.png") // implicit LogoMode(qrgode.LogoExclude)

// Overlay: render every module and stamp the logo on top. Scanners see
// more data, which helps when print quality varies. Pair with a transparent
// logo background if you want the QR pattern to show through.
qrgode.New(data).
    Logo("logo.png").
    LogoMode(qrgode.LogoOverlay).
    LogoBackground("transparent")

LogoPadding(0.05) tightens the space around the logo (default 0.1, fraction of the logo's longer side).

Examples

Generate to File
// SVG or PNG — chosen from the file extension
err := qrgode.New("https://example.com").
    Shape(qrgode.ShapeCircle).
    LinearGradient(45, "#667eea", "#764ba2").
    Logo("logo.png").
    SaveAs("output.png")
Generate to Bytes
svg, err := qrgode.New("https://example.com").SVG()
png, err := qrgode.New("https://example.com").PNG()
Stream to an io.Writer
// HTTP handler — no intermediate []byte allocation
func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "image/svg+xml")
    qrgode.New(r.URL.Query().Get("data")).WriteTo(w)
}
Validate Custom Images
// Validate before using
if err := qrgode.ValidateFinderImage("finder.png"); err != nil {
    log.Fatal(err)
}

if err := qrgode.ValidateLogoImage("logo.png"); err != nil {
    log.Fatal(err)
}

License

MIT License

Documentation

Overview

Package qrgode provides QR code generation with extensive customization.

Quick Start

The simplest way to generate a QR code:

svg, err := qrgode.Generate("https://example.com", nil)
if err != nil {
	log.Fatal(err)
}
os.WriteFile("qr.svg", svg, 0644)

Or save directly to a file:

err := qrgode.GenerateToFile("https://example.com", nil, "qr.svg")

Builder Pattern

For customization, use the fluent builder API:

qr := qrgode.New("https://example.com").
	Size(512).
	ErrorCorrection(qrgode.LevelH).
	Shape("circle").
	Foreground("#3498db").
	Background("#ffffff")

svg, err := qr.SVG()
png, err := qr.PNG()
// or save directly — format chosen from extension
err := qr.SaveAs("qr.png")

Gradients

Apply linear or radial gradients to modules:

// Linear gradient at 45 degrees
qr := qrgode.New("https://example.com").
	LinearGradient(45, "#ff0000", "#00ff00", "#0000ff")

// Radial gradient from center
qr := qrgode.New("https://example.com").
	RadialGradient(0.5, 0.5, "#ff0000", "#0000ff")

Custom Images

Use custom PNG/JPG images for QR elements:

qr := qrgode.New("https://example.com").
	ModuleImage("dot.png").        // Custom image for data modules
	FinderImage("finder.png").     // Custom image for finder patterns (7x7)
	AlignmentImage("align.png")    // Custom image for alignment patterns (5x5)

Add a logo in the center of the QR code:

// From file path
qr := qrgode.New("https://example.com").
	Logo("logo.png")

// From image.Image in memory
qr := qrgode.New("https://example.com").
	LogoImage(myImage)

Shapes

Available module shapes:

  • "square" (default)
  • "circle"
  • "rounded" (rounded corners)
  • "diamond"
  • "dot" (smaller circle)
  • "star"
  • "heart"

Error Correction Levels

Higher levels provide more redundancy but result in denser QR codes:

  • LevelL: ~7% recovery (smallest QR)
  • LevelM: ~15% recovery (default)
  • LevelQ: ~25% recovery
  • LevelH: ~30% recovery (densest QR)
Example (AdvancedConfig)
// For advanced usage, access the underlying config
qr := qrgode.New("https://example.com")
cfg := qr.GetConfig()

// Modify config directly
cfg.Size = 800
cfg.QuietZone = 2
cfg.Modules.Shape = "star"
cfg.Modules.Color = qrgode.NewLinearGradientColor(90, []string{"#e74c3c", "#9b59b6", "#3498db"})

svg, err := qr.SVG()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of SVG\n", len(svg))
Example (Basic)
// Simple QR code generation
svg, err := qrgode.Generate("https://example.com", nil)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of SVG\n", len(svg))
Example (Builder)
// Using the builder pattern for customization
qr := qrgode.New("https://example.com").
	Size(512).
	ErrorCorrection(qrgode.LevelH).
	Shape("circle").
	Foreground("#3498db").
	Background("#ffffff")

svg, err := qr.SVG()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of SVG\n", len(svg))
Example (CustomImages)
// Using custom images for QR elements
qr := qrgode.New("https://example.com").
	Size(512).
	ModuleImage("dot.png").
	FinderImage("finder.png").
	AlignmentImage("align.png")

// Note: This would fail without actual image files
_, _ = qr.SVG()
Example (Gradient)
// Linear gradient
qr := qrgode.New("https://example.com").
	Size(512).
	LinearGradient(45, "#ff0000", "#00ff00", "#0000ff").
	Shape("rounded")

svg, err := qr.SVG()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of SVG\n", len(svg))
Example (LogoOverlay)
// Overlay mode: render every module and stamp the logo on top, keeping
// more of the error-correction budget intact than exclude mode.
svg, err := qrgode.New("https://example.com").
	Logo("logo.png").
	LogoMode(qrgode.LogoOverlay).
	LogoBackground("transparent").
	LogoPadding(0.05).
	SVG()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of SVG\n", len(svg))
Example (Png)
// PNG output — supports every styling feature SVG does
png, err := qrgode.New("https://example.com").
	Size(512).
	Shape("heart").
	LinearGradient(45, "#ff6b6b", "#feca57").
	PNG()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of PNG\n", len(png))
Example (RadialGradient)
// Radial gradient from center
qr := qrgode.New("https://example.com").
	Size(512).
	RadialGradient(0.5, 0.5, "#ff6b6b", "#4ecdc4").
	Shape("dot")

svg, err := qr.SVG()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Generated %d bytes of SVG\n", len(svg))
Example (SaveToFile)
// Save directly to file
err := qrgode.New("https://example.com").
	Size(1024).
	Shape("diamond").
	Foreground("#2c3e50").
	SaveAs("my_qr.svg")

if err != nil {
	log.Fatal(err)
}
Example (ScannabilityCheck)
// Warn before generating if the logo + ECL combination is risky.
qr := qrgode.New("https://example.com").
	Logo("big-logo.png").
	ErrorCorrection(qrgode.LevelM)

for _, msg := range qr.ScannabilityWarnings() {
	fmt.Println("warning:", msg)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Generate

func Generate(data string, cfg *Config) ([]byte, error)

Generate creates a QR code from the given data and config. Returns SVG as a byte slice. If cfg is nil, DefaultConfig() is used.

func GeneratePNG added in v1.1.0

func GeneratePNG(data string, cfg *Config) ([]byte, error)

GeneratePNG creates a QR code and returns it as PNG bytes. If cfg is nil, DefaultConfig() is used.

func GenerateToFile

func GenerateToFile(data string, cfg *Config, path string) error

GenerateToFile creates a QR code and writes it to the specified path. The format is chosen from the file extension: .svg or .png.

func GenerateWithOptions

func GenerateWithOptions(data string, opts ...Option) ([]byte, error)

GenerateWithOptions creates a QR code using functional options.

func ValidateAlignmentImage

func ValidateAlignmentImage(path string) error

ValidateAlignmentImage validates an image intended for alignment patterns. Alignment patterns are 5x5 modules, so ideally the image should be square.

func ValidateConfig

func ValidateConfig(cfg *Config) []error

ValidateConfig validates the entire configuration. Returns a list of all validation errors found.

func ValidateFinderImage

func ValidateFinderImage(path string) error

ValidateFinderImage validates an image intended for finder patterns. Finder patterns are 7x7 modules, so ideally the image should be square.

func ValidateImage

func ValidateImage(path string) (width, height int, err error)

ValidateImage checks if the given path points to a valid image file. Returns the image dimensions if valid.

func ValidateLogoImage

func ValidateLogoImage(path string) error

ValidateLogoImage validates an image intended for the center logo.

func ValidateModuleImage

func ValidateModuleImage(path string) error

ValidateModuleImage validates an image intended for data modules.

Types

type AlignmentLayerStyle

type AlignmentLayerStyle struct {
	Shape string
	Color colors.Color
}

AlignmentLayerStyle defines one layer of an alignment pattern.

type AlignmentStyle

type AlignmentStyle struct {
	// Simple mode
	Shape string
	Color colors.Color

	// Detailed mode
	Outer  *AlignmentLayerStyle
	Center *AlignmentLayerStyle
}

AlignmentStyle defines how alignment patterns are rendered.

type Color

type Color = colors.Color

Color is an alias to the internal color interface for advanced usage. Most users should use the builder methods like Foreground(), LinearGradient(), etc.

func NewLinearGradientColor

func NewLinearGradientColor(angle float64, stops []string) Color

NewLinearGradientColor creates a linear gradient color. Angle is in degrees (0=right, 90=down, 180=left, 270=up).

func NewRadialGradientColor

func NewRadialGradientColor(centerX, centerY float64, stops []string) Color

NewRadialGradientColor creates a radial gradient color. Center coordinates are fractions from 0.0 to 1.0.

func NewSolidColor

func NewSolidColor(hex string) Color

NewSolidColor creates a solid color from a hex string. This is exported for advanced configuration via Config struct.

type Config

type Config struct {
	// QR data settings
	ErrorCorrection ErrorCorrectionLevel

	// Overall dimensions
	Size      int // Output size in pixels
	QuietZone int // Margin around QR (in modules)

	// Styling
	Background colors.Color
	Modules    ModuleStyle
	Finders    FinderStyle
	Alignment  AlignmentStyle
	Timing     TimingStyle

	// Custom images for elements
	Images *CustomImages
}

Config holds all configuration for QR code generation.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a config with sensible defaults.

type CustomImages

type CustomImages struct {
	Finder    string // Path to PNG for finder pattern modules (7x7 outer squares)
	Module    string // Path to PNG for regular data modules
	Alignment string // Path to PNG for alignment pattern modules (5x5 squares)
}

CustomImages defines custom PNG images for different QR elements.

type ErrorCorrectionLevel

type ErrorCorrectionLevel int

ErrorCorrectionLevel defines the amount of redundancy in the QR code. Higher levels provide more error recovery but result in denser codes.

const (
	LevelL ErrorCorrectionLevel = iota // ~7% recovery capacity
	LevelM                             // ~15% recovery capacity (default)
	LevelQ                             // ~25% recovery capacity
	LevelH                             // ~30% recovery capacity
)

type FinderLayerStyle

type FinderLayerStyle struct {
	Shape        string
	Color        colors.Color
	CornerRadius float64 // For rounded shapes
}

FinderLayerStyle defines one layer of a finder pattern.

type FinderStyle

type FinderStyle struct {
	// Simple mode: style all three layers uniformly
	Shape string
	Color colors.Color

	// Detailed mode: style each layer separately
	Outer  *FinderLayerStyle
	Middle *FinderLayerStyle
	Center *FinderLayerStyle
}

FinderStyle defines how finder patterns are rendered.

type LogoConfig

type LogoConfig struct {
	Path       string      // Path to logo image file
	Image      image.Image // In-memory logo image (takes precedence over Path)
	Width      int         // Optional: logo width in pixels (0 = auto-calculate)
	Height     int         // Optional: logo height in pixels (0 = auto-calculate)
	Background string      // Background color behind logo (hex or "transparent", default white)
	Mode       LogoMode    // LogoExclude (default) or LogoOverlay
	Padding    float64     // Padding around the logo as a fraction of its longer side. 0 = default (0.1).
}

LogoConfig defines the logo overlay settings.

type LogoMode added in v1.2.0

type LogoMode int

LogoMode controls how the logo interacts with the QR modules.

const (
	// LogoExclude (default) skips the modules behind the logo so the scanner
	// never sees them. The QR's error-correction budget must absorb the loss.
	LogoExclude LogoMode = iota
	// LogoOverlay renders every module and stamps the logo on top. Scanners
	// see whatever isn't physically occluded, leaving more of the
	// error-correction budget intact for print-quality variance.
	LogoOverlay
)

type ModuleStyle

type ModuleStyle struct {
	Shape string       // Shape name or SVG path
	Color colors.Color // Solid, gradient, or image-sampled
	Size  float64      // Size as fraction of cell (0.0-1.0)
}

ModuleStyle defines how data modules are rendered.

type Option

type Option func(*Config)

Option is a functional option for configuring QR generation.

func WithErrorCorrection

func WithErrorCorrection(level ErrorCorrectionLevel) Option

WithErrorCorrection sets the error correction level.

func WithLogo(path string) Option

WithLogo sets the logo path. Size is auto-calculated.

func WithLogoSize

func WithLogoSize(path string, width, height int) Option

WithLogoSize sets logo path with custom dimensions. Pass 0 for width or height to auto-calculate that dimension.

func WithModuleShape

func WithModuleShape(shape string) Option

WithModuleShape sets the shape for data modules.

func WithQuietZone

func WithQuietZone(modules int) Option

WithQuietZone sets the margin around the QR code.

func WithSize

func WithSize(size int) Option

WithSize sets the output size in pixels.

type QRCode

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

QRCode represents a QR code generator with fluent configuration.

func New

func New(data string) *QRCode

New creates a new QR code generator for the given data.

Example:

qr := qrcode.New("https://example.com")
svg, err := qr.SVG()

func (*QRCode) AlignmentImage

func (q *QRCode) AlignmentImage(path string) *QRCode

AlignmentImage sets a custom image for alignment patterns. The image represents the full 5x5 alignment pattern (smaller squares in larger QR codes). The image is validated immediately; errors are collected and returned by SVG()/SaveAs().

func (*QRCode) Background

func (q *QRCode) Background(hex string) *QRCode

Background sets the background color as a hex string.

Example: "#ffffff", "#f0f0f0", "transparent"

func (*QRCode) ErrorCorrection

func (q *QRCode) ErrorCorrection(level ErrorCorrectionLevel) *QRCode

ErrorCorrection sets the error correction level. Default is LevelM.

Available levels:

  • LevelL: ~7% recovery
  • LevelM: ~15% recovery (default)
  • LevelQ: ~25% recovery
  • LevelH: ~30% recovery

func (*QRCode) FinderImage

func (q *QRCode) FinderImage(path string) *QRCode

FinderImage sets a custom image for finder patterns. The image represents the full 7x7 finder pattern (the big squares in corners). It will be mirrored appropriately for each corner. The image is validated immediately; errors are collected and returned by SVG()/SaveAs().

func (*QRCode) Foreground

func (q *QRCode) Foreground(hex string) *QRCode

Foreground sets the foreground color (modules) as a hex string.

Example: "#000000", "#3498db", "rgb(52, 152, 219)"

func (*QRCode) GetConfig

func (q *QRCode) GetConfig() *Config

GetConfig returns the underlying configuration for advanced customization.

func (*QRCode) LinearGradient

func (q *QRCode) LinearGradient(angle float64, colorStops ...string) *QRCode

LinearGradient sets a linear gradient for the modules.

Parameters:

  • angle: Direction in degrees (0=right, 90=down, 180=left, 270=up)
  • colorStops: At least 2 hex color strings

Example:

qr.LinearGradient(45, "#ff0000", "#0000ff")
func (q *QRCode) Logo(path string) *QRCode

Logo sets a logo image from a file path to display in the center of the QR code. The logo will have a white background padding by default.

func (*QRCode) LogoBackground

func (q *QRCode) LogoBackground(color string) *QRCode

LogoBackground sets the background color behind the logo. Use hex color (e.g., "#ffffff") or "transparent" for no background.

func (*QRCode) LogoDimensions

func (q *QRCode) LogoDimensions(width, height int) *QRCode

LogoDimensions sets both logo width and height in pixels.

func (*QRCode) LogoHeight

func (q *QRCode) LogoHeight(pixels int) *QRCode

LogoHeight sets the logo height in pixels. Width will be calculated to preserve aspect ratio. If not set, logo size is auto-calculated to fit within 15-30% of QR size.

func (*QRCode) LogoImage

func (q *QRCode) LogoImage(img image.Image) *QRCode

LogoImage sets an in-memory image as the logo to display in the center of the QR code. This takes precedence over Logo() if both are set. The logo will have a white background padding by default.

func (*QRCode) LogoMode added in v1.2.0

func (q *QRCode) LogoMode(mode LogoMode) *QRCode

LogoMode controls whether the modules behind the logo are skipped (LogoExclude, default) or rendered with the logo composited on top (LogoOverlay). Overlay keeps the error-correction budget intact.

func (*QRCode) LogoPadding added in v1.2.0

func (q *QRCode) LogoPadding(fraction float64) *QRCode

LogoPadding sets the padding around the logo as a fraction of its longer side. Default is 0.1 (10%). Smaller values pack modules tighter to the logo; pass 0 to revert to the default.

func (*QRCode) LogoWidth

func (q *QRCode) LogoWidth(pixels int) *QRCode

LogoWidth sets the logo width in pixels. Height will be calculated to preserve aspect ratio. If not set, logo size is auto-calculated to fit within 15-30% of QR size.

func (*QRCode) ModuleImage

func (q *QRCode) ModuleImage(path string) *QRCode

ModuleImage sets a custom PNG/JPG/SVG image for data modules. Each module will be rendered using this image. The image is validated immediately; errors are collected and returned by SVG()/SaveAs().

func (*QRCode) PNG added in v1.1.0

func (q *QRCode) PNG() ([]byte, error)

PNG generates and returns the QR code as PNG bytes. PNG output is rasterized from the SVG pipeline, so it supports the same shapes, gradients, custom images, and logos as SVG().

func (*QRCode) QuietZone

func (q *QRCode) QuietZone(modules int) *QRCode

QuietZone sets the margin around the QR code in modules. Default is 4.

func (*QRCode) RadialGradient

func (q *QRCode) RadialGradient(centerX, centerY float64, colorStops ...string) *QRCode

RadialGradient sets a radial gradient for the modules.

Parameters:

  • centerX, centerY: Center position as fractions (0.0-1.0)
  • colorStops: At least 2 hex color strings

Example:

qr.RadialGradient(0.5, 0.5, "#ff0000", "#0000ff")

func (*QRCode) SVG

func (q *QRCode) SVG() ([]byte, error)

SVG generates and returns the QR code as SVG bytes. Returns an error if validation fails or encoding fails.

func (*QRCode) SVGString

func (q *QRCode) SVGString() (string, error)

SVGString generates and returns the QR code as an SVG string.

func (*QRCode) SaveAs

func (q *QRCode) SaveAs(path string) error

SaveAs generates the QR code and saves it to the specified file. The format is chosen from the file extension: .svg or .png.

func (*QRCode) ScannabilityWarnings added in v1.1.0

func (q *QRCode) ScannabilityWarnings() []string

ScannabilityWarnings inspects the configuration for combinations that commonly produce unscannable QR codes — currently, a logo that occupies more of the QR area than the chosen error-correction level can recover.

Warnings are heuristic and free of side effects: nothing is printed. Call this before SVG()/PNG() if you want to surface them to your users.

Returns nil if no logo is configured or the configuration is safe.

func (*QRCode) Shape

func (q *QRCode) Shape(shape Shape) *QRCode

Shape sets the module shape.

Available shapes: ShapeSquare, ShapeCircle, ShapeRounded, ShapeDiamond, ShapeDot, ShapeStar, ShapeHeart

func (*QRCode) Size

func (q *QRCode) Size(pixels int) *QRCode

Size sets the output size in pixels. Default is 256.

func (*QRCode) Validate

func (q *QRCode) Validate() []error

Validate checks the configuration and returns any validation errors. This is called automatically by SVG() and SaveAs(), but can be called explicitly to check configuration before generation.

func (*QRCode) WriteTo added in v1.1.0

func (q *QRCode) WriteTo(w io.Writer) (int64, error)

WriteTo generates the QR code and streams the SVG bytes to w. It implements io.WriterTo, making it convenient for HTTP handlers:

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "image/svg+xml")
    qrgode.New(r.URL.Query().Get("data")).WriteTo(w)
}

type Shape

type Shape string

Shape defines the module shape for QR code rendering.

const (
	ShapeSquare  Shape = "square"  // Default square modules
	ShapeCircle  Shape = "circle"  // Circular modules
	ShapeRounded Shape = "rounded" // Rounded corner squares
	ShapeDiamond Shape = "diamond" // Diamond/rotated squares
	ShapeDot     Shape = "dot"     // Smaller circular dots
	ShapeStar    Shape = "star"    // Star shaped modules
	ShapeHeart   Shape = "heart"   // Heart shaped modules
)

type TimingStyle

type TimingStyle struct {
	Shape string
	Color colors.Color
}

TimingStyle defines how timing patterns are rendered.

type UnsupportedFormatError

type UnsupportedFormatError struct {
	Format string
}

UnsupportedFormatError is returned when an unsupported output format is requested.

func (*UnsupportedFormatError) Error

func (e *UnsupportedFormatError) Error() string

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents an error during configuration validation.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
cmd
gen-showcase command
Generates the README showcase SVGs into assets/showcase/.
Generates the README showcase SVGs into assets/showcase/.
qr-gode command
show-alignment command
test-versions command
internal

Jump to

Keyboard shortcuts

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