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)
Logo ¶
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 ¶
- func Generate(data string, cfg *Config) ([]byte, error)
- func GeneratePNG(data string, cfg *Config) ([]byte, error)
- func GenerateToFile(data string, cfg *Config, path string) error
- func GenerateWithOptions(data string, opts ...Option) ([]byte, error)
- func ValidateAlignmentImage(path string) error
- func ValidateConfig(cfg *Config) []error
- func ValidateFinderImage(path string) error
- func ValidateImage(path string) (width, height int, err error)
- func ValidateLogoImage(path string) error
- func ValidateModuleImage(path string) error
- type AlignmentLayerStyle
- type AlignmentStyle
- type Color
- type Config
- type CustomImages
- type ErrorCorrectionLevel
- type FinderLayerStyle
- type FinderStyle
- type LogoConfig
- type LogoMode
- type ModuleStyle
- type Option
- type QRCode
- func (q *QRCode) AlignmentImage(path string) *QRCode
- func (q *QRCode) Background(hex string) *QRCode
- func (q *QRCode) ErrorCorrection(level ErrorCorrectionLevel) *QRCode
- func (q *QRCode) FinderImage(path string) *QRCode
- func (q *QRCode) Foreground(hex string) *QRCode
- func (q *QRCode) GetConfig() *Config
- func (q *QRCode) LinearGradient(angle float64, colorStops ...string) *QRCode
- func (q *QRCode) Logo(path string) *QRCode
- func (q *QRCode) LogoBackground(color string) *QRCode
- func (q *QRCode) LogoDimensions(width, height int) *QRCode
- func (q *QRCode) LogoHeight(pixels int) *QRCode
- func (q *QRCode) LogoImage(img image.Image) *QRCode
- func (q *QRCode) LogoMode(mode LogoMode) *QRCode
- func (q *QRCode) LogoPadding(fraction float64) *QRCode
- func (q *QRCode) LogoWidth(pixels int) *QRCode
- func (q *QRCode) ModuleImage(path string) *QRCode
- func (q *QRCode) PNG() ([]byte, error)
- func (q *QRCode) QuietZone(modules int) *QRCode
- func (q *QRCode) RadialGradient(centerX, centerY float64, colorStops ...string) *QRCode
- func (q *QRCode) SVG() ([]byte, error)
- func (q *QRCode) SVGString() (string, error)
- func (q *QRCode) SaveAs(path string) error
- func (q *QRCode) ScannabilityWarnings() []string
- func (q *QRCode) Shape(shape Shape) *QRCode
- func (q *QRCode) Size(pixels int) *QRCode
- func (q *QRCode) Validate() []error
- func (q *QRCode) WriteTo(w io.Writer) (int64, error)
- type Shape
- type TimingStyle
- type UnsupportedFormatError
- type ValidationError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Generate ¶
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
GeneratePNG creates a QR code and returns it as PNG bytes. If cfg is nil, DefaultConfig() is used.
func GenerateToFile ¶
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 ¶
GenerateWithOptions creates a QR code using functional options.
func ValidateAlignmentImage ¶
ValidateAlignmentImage validates an image intended for alignment patterns. Alignment patterns are 5x5 modules, so ideally the image should be square.
func ValidateConfig ¶
ValidateConfig validates the entire configuration. Returns a list of all validation errors found.
func ValidateFinderImage ¶
ValidateFinderImage validates an image intended for finder patterns. Finder patterns are 7x7 modules, so ideally the image should be square.
func ValidateImage ¶
ValidateImage checks if the given path points to a valid image file. Returns the image dimensions if valid.
func ValidateLogoImage ¶
ValidateLogoImage validates an image intended for the center logo.
func ValidateModuleImage ¶
ValidateModuleImage validates an image intended for data modules.
Types ¶
type AlignmentLayerStyle ¶
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 ¶
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 ¶
NewLinearGradientColor creates a linear gradient color. Angle is in degrees (0=right, 90=down, 180=left, 270=up).
func NewRadialGradientColor ¶
NewRadialGradientColor creates a radial gradient color. Center coordinates are fractions from 0.0 to 1.0.
func NewSolidColor ¶
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
Logo *LogoConfig
// 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 WithLogoSize ¶
WithLogoSize sets logo path with custom dimensions. Pass 0 for width or height to auto-calculate that dimension.
func WithModuleShape ¶
WithModuleShape sets the shape for data modules.
func WithQuietZone ¶
WithQuietZone sets the margin around the QR code.
type QRCode ¶
type QRCode struct {
// contains filtered or unexported fields
}
QRCode represents a QR code generator with fluent configuration.
func New ¶
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 ¶
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 ¶
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 ¶
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 ¶
Foreground sets the foreground color (modules) as a hex string.
Example: "#000000", "#3498db", "rgb(52, 152, 219)"
func (*QRCode) GetConfig ¶
GetConfig returns the underlying configuration for advanced customization.
func (*QRCode) LinearGradient ¶
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 (*QRCode) Logo ¶
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 ¶
LogoBackground sets the background color behind the logo. Use hex color (e.g., "#ffffff") or "transparent" for no background.
func (*QRCode) LogoDimensions ¶
LogoDimensions sets both logo width and height in pixels.
func (*QRCode) LogoHeight ¶
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 ¶
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
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
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 ¶
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 ¶
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
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) RadialGradient ¶
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 ¶
SVG generates and returns the QR code as SVG bytes. Returns an error if validation fails or encoding fails.
func (*QRCode) SaveAs ¶
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
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 ¶
Shape sets the module shape.
Available shapes: ShapeSquare, ShapeCircle, ShapeRounded, ShapeDiamond, ShapeDot, ShapeStar, ShapeHeart
func (*QRCode) Validate ¶
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
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 ¶
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 ¶
ValidationError represents an error during configuration validation.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
create-test-images
command
|
|
|
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
|
|
