Documentation
¶
Overview ¶
Package renderer provides QR code rendering in multiple output formats including PNG, SVG, PDF, terminal Unicode, and base64 with support for custom module styles, gradients, and transparency.
The package uses a functional-options pattern for configuration. Each renderer implements a common Render method that accepts a variadic list of RenderOption values, making it easy to compose complex rendering configurations.
Quick Start ¶
r := renderer.NewPNGRenderer() err := r.Render(ctx, qrCode, os.Stdout)
Custom Styling ¶
err := r.Render(ctx, qrCode, os.Stdout,
renderer.WithGradient("#FF0000", "#0000FF", 45),
renderer.WithRoundedModules(0.5),
renderer.WithTransparency(0.8),
renderer.WithForegroundColor("#000000"),
renderer.WithBackgroundColor("#FFFFFF"),
)
Module Shapes ¶
The renderer supports four module shapes: "square", "rounded", "circle", and "diamond". Shape can be set via WithRoundedModules, WithCircleModules, or by constructing a ModuleStyle directly and passing it to WithModuleStyle.
Gradient Fills ¶
Linear gradient fills are supported for PNG and SVG output formats. Use WithGradient to specify start color, end color, and angle:
err := r.Render(ctx, qrCode, os.Stdout,
renderer.WithGradient("#4A00E0", "#8E2DE2", 135),
)
Supported Formats ¶
- PNG: raster image with full module-style support
- SVG: vector graphic with gradient and shape support
- PDF: document output (PDF 1.4)
- Terminal: Unicode block characters with ANSI color support
- Base64: base64-encoded PNG data URI for embedding in HTML/CSS
Index ¶
- func ApplyTransparency(c color.Color, alpha float64) color.RGBA
- func DrawCircle(img *image.RGBA, cx, cy, radius int, c color.Color)
- func DrawDiamond(img *image.RGBA, cx, cy, halfW, halfH int, c color.Color)
- func DrawModule(img *image.RGBA, x, y, scale int, style *ModuleStyle, fgColor color.Color)
- func DrawRoundedRect(img *image.RGBA, x, y, w, h, radius int, c color.Color)
- func Encode(qr *encoding.QRCode) (string, error)
- func EncodeRaw(qr *encoding.QRCode) (string, error)
- func GradientColor(x, y, width, height int, angle float64, start, end color.RGBA) color.RGBA
- func GradientColorAt(px, py, width, height int, angle float64, start, end color.RGBA) color.RGBA
- func InterpolateColor(start, end color.RGBA, t float64) color.RGBA
- func IsGradientStyle(style *ModuleStyle) bool
- func NeedsAdvancedSVG(style *ModuleStyle) bool
- func ParseGradient(startHex, endHex string) (color.RGBA, color.RGBA, error)
- func ParseHexColor(hex string) (uint8, uint8, uint8, error)
- func SVGCircle(col, row, scale int, color, fill string) string
- func SVGDiamond(col, row, scale int, color, fill string) string
- func SVGGradientDef(startColor, endColor string, angle float64, id string) string
- func SVGGradientDefinition(startColor, endColor string, angle float64, id string) string
- func SVGModule(col, row, scale int, style *ModuleStyle, color string) string
- func SVGModuleAttributes(col, row, scale int, style *ModuleStyle, fgColor string) string
- func SVGRoundedRect(col, row, scale int, color, fill string, roundness float64) string
- func SVGRoundedRectPath(x, y, w, h, r float64) string
- func ScaleSize(matrixSize, quietZone, targetPixels int) int
- type Base64Renderer
- func (r *Base64Renderer) ContentType() string
- func (r *Base64Renderer) Render(ctx context.Context, qr *encoding.QRCode, w io.Writer, opts ...RenderOption) error
- func (r *Base64Renderer) RenderDataURL(ctx context.Context, qr *encoding.QRCode, opts ...RenderOption) (string, error)
- func (r *Base64Renderer) RenderToString(ctx context.Context, qr *encoding.QRCode, opts ...RenderOption) (string, error)
- func (r *Base64Renderer) Type() string
- type Format
- type ModuleStyle
- type PDFRenderer
- type PNGRenderer
- type RenderConfig
- type RenderOption
- func WithBackgroundColor(color string) RenderOption
- func WithBorderWidth(bw int) RenderOption
- func WithCircleModules() RenderOption
- func WithForegroundColor(color string) RenderOption
- func WithGradient(startColor, endColor string, angle float64) RenderOption
- func WithHeight(h int) RenderOption
- func WithModuleStyle(style *ModuleStyle) RenderOption
- func WithQuietZone(qz int) RenderOption
- func WithRoundedModules(roundness float64) RenderOption
- func WithTransparency(alpha float64) RenderOption
- func WithWidth(w int) RenderOption
- type SVGRenderer
- type TerminalRenderer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyTransparency ¶
ApplyTransparency returns a copy of the color with the alpha channel set to the given value. The alpha parameter is clamped to [0.0, 1.0] and converted to an 8-bit value (0–255). The RGB channels are preserved.
func DrawCircle ¶
DrawCircle draws a filled circle onto the image using the midpoint distance test. Pixels within radius distance of (cx, cy) are painted.
Parameters:
- img: target RGBA image
- cx, cy: center coordinates
- radius: circle radius in pixels
- c: fill color
func DrawDiamond ¶
DrawDiamond draws a filled diamond (rhombus) shape onto the image. The diamond is centered at (cx, cy) with horizontal half-width halfW and vertical half-height halfH. A pixel at (px, py) is inside the diamond when |dx|/halfW + |dy|/halfH ≤ 1.0.
Parameters:
- img: target RGBA image
- cx, cy: center coordinates
- halfW, halfH: horizontal and vertical half-sizes in pixels
- c: fill color
func DrawModule ¶
DrawModule renders a single QR code module onto the image at position (x, y) with the given pixel scale and style.
For square modules (or nil style), the module cell is filled directly. For other shapes, DrawModule dispatches to the appropriate drawing function:
- "rounded" → DrawRoundedRect with radius = scale * roundness * 0.5
- "circle" → DrawCircle inscribed in the module cell
- "diamond" → DrawDiamond inscribed in the module cell
If the style has GradientEnabled, the gradient color at the module's position is computed and used as the fill color. If Transparency < 1.0, the alpha channel is adjusted accordingly.
func DrawRoundedRect ¶
DrawRoundedRect draws a filled rounded rectangle onto the image.
The radius parameter controls the corner curvature. If radius exceeds half the width or half the height, it is clamped to the smaller of the two. Negative radii are clamped to zero. Pixels that fall outside the rounded corners (i.e., beyond the arc at each corner) are not painted.
Parameters:
- img: target RGBA image
- x, y: top-left corner of the rectangle
- w, h: width and height in pixels
- radius: corner radius in pixels
- c: fill color
func Encode ¶
Encode is a convenience function that renders a QR code as a base64 PNG data URI string using default render options. It is equivalent to:
renderer.NewBase64Renderer().RenderDataURL(context.Background(), qr)
func EncodeRaw ¶
EncodeRaw is a convenience function that renders a QR code as raw base64-encoded PNG bytes (without the data URI prefix) using default render options. It is equivalent to:
renderer.NewBase64Renderer().RenderToString(context.Background(), qr)
func GradientColor ¶
GradientColor computes the gradient color at pixel position (x, y) for a linear gradient with the given angle over an image of the specified dimensions.
The gradient direction is determined by angle (in degrees, clockwise from the x-axis). The interpolation factor t is computed by projecting the point onto the gradient axis and normalising against the image diagonal. Returns start if width or height is zero.
func GradientColorAt ¶
GradientColorAt computes the linear gradient color at pixel position (px, py) for an image of the given dimensions and gradient angle.
The interpolation is based on projecting the point onto the gradient direction vector (defined by angle in degrees) and normalising against the maximum possible projection distance across the image. The result is clamped to [0.0, 1.0] before interpolating between start and end colors.
This function differs from GradientColor in that it uses a centered projection for more uniform gradient distribution across the image.
Parameters:
- px, py: pixel coordinates
- width, height: image dimensions
- angle: gradient angle in degrees (0° = right, 90° = down)
- start: gradient start color
- end: gradient end color
func InterpolateColor ¶
InterpolateColor linearly interpolates between two RGBA colors by factor t. The factor t is clamped to [0.0, 1.0]. At t=0 the result equals start; at t=1 the result equals end. Each channel (R, G, B, A) is interpolated independently.
func IsGradientStyle ¶
func IsGradientStyle(style *ModuleStyle) bool
IsGradientStyle reports whether the module style uses a gradient fill. Returns false if the style is nil.
func NeedsAdvancedSVG ¶
func NeedsAdvancedSVG(style *ModuleStyle) bool
NeedsAdvancedSVG reports whether the module style requires non-trivial SVG rendering (any shape other than "square"). Returns false if the style is nil or uses the default square shape.
func ParseGradient ¶
ParseGradient parses two "#RRGGBB" hex color strings into RGBA colors suitable for gradient interpolation. Both colors are returned with alpha set to 255 (fully opaque). Returns an error if either color string is malformed.
func ParseHexColor ¶
ParseHexColor parses a "#RRGGBB" hex color string into its red, green, and blue components (each 0–255). The input must be exactly 7 characters long and start with '#'. Returns an error for malformed inputs.
Example:
r, g, b, err := renderer.ParseHexColor("#1A2B3C")
// r=26, g=43, b=60, err=nil
func SVGCircle ¶
SVGCircle returns an SVG <circle> element string centered in the module cell at grid position (col, row). The radius is half the module scale.
Parameters:
- col, row: module grid position
- scale: pixel size of each module
- color: CSS fill color
- fill: CSS opacity value
func SVGDiamond ¶
SVGDiamond returns an SVG <polygon> element string representing a diamond (rotated square) inscribed in the module cell at grid position (col, row). The four vertices are at the top-center, right-center, bottom-center, and left-center of the module cell.
Parameters:
- col, row: module grid position
- scale: pixel size of each module
- color: CSS fill color
- fill: CSS opacity value
func SVGGradientDef ¶
SVGGradientDef returns an SVG <defs> block containing a <linearGradient> element with the specified colors and angle.
The gradient direction is computed from the angle in degrees by projecting from the center of the coordinate system. The x1/y1/x2/y2 attributes are expressed as percentages (0–100%).
Parameters:
- startColor: gradient start color as a CSS color string (e.g., "#FF0000")
- endColor: gradient end color as a CSS color string
- angle: gradient angle in degrees
- id: unique identifier for the gradient (referenced via url(#id))
Example output:
<defs><linearGradient id="qr-gradient" x1="0.0%" y1="100.0%" ... <stop offset="0%" stop-color="#FF0000"/> <stop offset="100%" stop-color="#0000FF"/> </linearGradient></defs>
func SVGGradientDefinition ¶
SVGGradientDefinition returns an SVG <defs> block containing a <linearGradient> element with objectBoundingBox gradient units.
The angle is adjusted by -90° so that 0° maps to a left-to-right gradient (matching CSS linear-gradient conventions). The x1/y1/x2/y2 coordinates are expressed as fractions in [0, 1].
Parameters:
- startColor: gradient start color as a CSS color string
- endColor: gradient end color as a CSS color string
- angle: gradient angle in degrees (0° = left-to-right after adjustment)
- id: unique identifier for the gradient element
func SVGModule ¶
func SVGModule(col, row, scale int, style *ModuleStyle, color string) string
SVGModule returns the SVG element string for a single QR code module at grid position (col, row). It selects the appropriate SVG primitive based on the ModuleStyle:
- nil or "square" → <rect> element
- "rounded" → SVGRoundedRect
- "circle" → SVGCircle
- "diamond" → SVGDiamond
If the style has GradientEnabled, the fill is set to "url(#qr-gradient)". If Transparency > 0, an opacity attribute is added.
func SVGModuleAttributes ¶
func SVGModuleAttributes(col, row, scale int, style *ModuleStyle, fgColor string) string
SVGModuleAttributes returns a complete SVG element string (including tag name and attributes) for a module at grid position (col, row) with pixel size scale. This function selects the appropriate SVG element based on the ModuleStyle:
- nil or "square" → <rect> with x, y, width, height
- "rounded" → <path> using SVGRoundedRectPath
- "circle" → <circle> with cx, cy, r
- "diamond" → <polygon> with four vertices
If GradientEnabled is set, the fill references "url(#qrgradient)". If Transparency < 1.0, an opacity attribute is added.
This is used by the advanced SVG rendering path in the SVGRenderer.
func SVGRoundedRect ¶
SVGRoundedRect returns an SVG <rect> element string with rounded corners. The corner radius is computed as roundness * scale * 0.5. The fill and opacity are passed as CSS-compatible string values.
Parameters:
- col, row: module grid position
- scale: pixel size of each module
- color: CSS fill color (or url(#gradient-id) for gradients)
- fill: CSS opacity value (e.g., "1" or "0.85")
- roundness: corner radius factor in [0.0, 1.0]
func SVGRoundedRectPath ¶
SVGRoundedRectPath returns an SVG path "d" attribute string for a rounded rectangle using arc commands. The path traces the rectangle starting from the top-left edge (after the corner radius), moving clockwise with four arc segments at each corner.
If the radius is zero, a simple path using only H (horizontal) and V (vertical) line-to commands is returned. The radius is clamped to [0, min(w, h)/2].
Parameters:
- x, y: top-left corner coordinates
- w, h: width and height
- r: corner radius
Example output:
M10.0,10.0 H20.0 A2.0,2.0 0 0,1 22.0,12.0 V20.0 ... Z
Types ¶
type Base64Renderer ¶
type Base64Renderer struct {
// contains filtered or unexported fields
}
Base64Renderer renders QR codes as base64-encoded PNG data URIs.
This renderer wraps a PNGRenderer and encodes its output into base64. It is designed for scenarios where the QR code needs to be embedded directly in HTML <img> tags or CSS background-image properties.
The renderer delegates all rendering options (including module styles, gradients, and transparency) to the underlying PNGRenderer.
Example:
r := renderer.NewBase64Renderer() dataURI, err := r.RenderDataURL(ctx, qr) // dataURI = "data:image/png;base64,iVBORw0KGgo..."
func NewBase64Renderer ¶
func NewBase64Renderer() *Base64Renderer
NewBase64Renderer creates a new Base64Renderer with an underlying PNGRenderer. The returned renderer is stateless and safe for concurrent use.
func (*Base64Renderer) ContentType ¶
func (r *Base64Renderer) ContentType() string
ContentType returns the MIME type "text/plain".
func (*Base64Renderer) Render ¶
func (r *Base64Renderer) Render(ctx context.Context, qr *encoding.QRCode, w io.Writer, opts ...RenderOption) error
Render writes the QR code as a base64 PNG data URI to w. The output format is: data:image/png;base64,<base64-encoded-png-bytes>. All standard RenderOptions (including module styles) are supported.
func (*Base64Renderer) RenderDataURL ¶
func (r *Base64Renderer) RenderDataURL(ctx context.Context, qr *encoding.QRCode, opts ...RenderOption) (string, error)
RenderDataURL renders the QR code and returns a complete data URI string in the form "data:image/png;base64,<base64>". This value can be used directly as the src attribute of an HTML <img> tag.
func (*Base64Renderer) RenderToString ¶
func (r *Base64Renderer) RenderToString(ctx context.Context, qr *encoding.QRCode, opts ...RenderOption) (string, error)
RenderToString renders the QR code and returns the raw base64-encoded PNG bytes as a string, without the data URI prefix. This is useful when you need only the base64 payload for custom URI schemes or API payloads.
func (*Base64Renderer) Type ¶
func (r *Base64Renderer) Type() string
Type returns the format identifier "base64".
type Format ¶
type Format int
Format enumerates the supported rendering output formats.
Each format has an associated renderer type that implements the Render(context.Context, *encoding.QRCode, io.Writer, ...RenderOption) method.
type ModuleStyle ¶
type ModuleStyle struct {
// Shape is the module shape. Accepted values are:
// - "square" (default): standard rectangular modules
// - "rounded": rounded rectangles; corner radius controlled by Roundness
// - "circle": each module rendered as a circle inscribed in the module cell
// - "diamond": each module rendered as a diamond (rotated square)
Shape string
// Roundness controls the corner radius for rounded modules.
// The value is clamped to [0.0, 1.0] where 0.0 produces sharp corners
// and 1.0 produces a circle. Only meaningful when Shape is "rounded".
Roundness float64
// GradientEnabled enables a linear gradient fill on modules.
// When true, the GradientStart and GradientEnd colors are used instead
// of the renderer's ForegroundColor. Supported by PNG and SVG renderers.
GradientEnabled bool
// GradientStart is the gradient start color as a hex string ("#RRGGBB").
// Ignored unless GradientEnabled is true.
GradientStart string
// GradientEnd is the gradient end color as a hex string ("#RRGGBB").
// Ignored unless GradientEnabled is true.
GradientEnd string
// GradientAngle is the linear gradient angle in degrees, measured
// clockwise from the positive x-axis. For example, 0° is left-to-right,
// 90° is top-to-bottom, and 135° is diagonal top-left to bottom-right.
GradientAngle float64
// Transparency controls the module opacity (alpha channel). A value of
// 1.0 means fully opaque and 0.0 means fully transparent.
Transparency float64
}
ModuleStyle controls the visual appearance of individual QR code modules.
A ModuleStyle can customize the shape of each dark module, apply linear gradient fills, and set transparency (alpha). Use the convenience option functions WithGradient, WithRoundedModules, WithCircleModules, and WithTransparency to build a ModuleStyle incrementally, or construct one directly and pass it to WithModuleStyle.
Example (direct construction):
style := &renderer.ModuleStyle{
Shape: "rounded",
Roundness: 0.6,
GradientEnabled: true,
GradientStart: "#FF0000",
GradientEnd: "#0000FF",
GradientAngle: 90,
Transparency: 0.85,
}
err := r.Render(ctx, qr, os.Stdout, renderer.WithModuleStyle(style))
func DefaultModuleStyle ¶
func DefaultModuleStyle() *ModuleStyle
DefaultModuleStyle returns a ModuleStyle with default square shape, no gradient, and full opacity (Transparency 1.0). This is the starting point for all convenience option functions (WithGradient, WithRoundedModules, etc.) that need to initialize a ModuleStyle when none is set.
func (*ModuleStyle) IsCircle ¶
func (s *ModuleStyle) IsCircle() bool
IsCircle reports whether the module shape is "circle". Returns false if the receiver is nil.
func (*ModuleStyle) IsGradientEnabled ¶
func (s *ModuleStyle) IsGradientEnabled() bool
IsGradientEnabled reports whether gradient fill is active. Returns false if the receiver is nil.
func (*ModuleStyle) IsRounded ¶
func (s *ModuleStyle) IsRounded() bool
IsRounded reports whether the module shape is "rounded". Returns false if the receiver is nil.
func (*ModuleStyle) Validate ¶
func (s *ModuleStyle) Validate() error
Validate checks that the module style parameters are valid. It returns an error if:
- Shape is not one of "square", "rounded", "circle", or "diamond";
- Roundness is outside [0.0, 1.0];
- Transparency is outside [0.0, 1.0];
- Gradient is enabled but start or end color is not a valid "#RRGGBB" hex string.
A nil receiver is always valid and returns nil.
type PDFRenderer ¶
type PDFRenderer struct{}
PDFRenderer renders QR codes as PDF (Portable Document Format) documents.
The renderer produces a minimal, self-contained PDF 1.4 file with a single page containing the QR code. Each dark module is drawn as a filled rectangle using the PDF content stream operator "re" (rectangle) with the fill operator "f". Colors are specified in DeviceRGB color space.
The page dimensions are automatically computed to fit the QR code plus quiet zone and any configured border width, with an additional one-module margin.
Example:
r := renderer.NewPDFRenderer()
err := r.Render(ctx, qr, os.Stdout,
renderer.WithForegroundColor("#000000"),
renderer.WithBorderWidth(10),
)
func NewPDFRenderer ¶
func NewPDFRenderer() *PDFRenderer
NewPDFRenderer creates a new PDFRenderer. The returned renderer is stateless and safe for concurrent use.
func (*PDFRenderer) ContentType ¶
func (r *PDFRenderer) ContentType() string
ContentType returns the MIME type "application/pdf".
func (*PDFRenderer) Render ¶
func (r *PDFRenderer) Render(_ context.Context, qr *encoding.QRCode, w io.Writer, opts ...RenderOption) error
Render writes the QR code as a PDF 1.4 document to w using the given render options.
The generated PDF contains a catalog, page tree, single page, and a content stream object. Module size is fixed at 10pt. The page size is computed as (qrSize + 2*quietZone)*moduleSize + 2*(borderWidth + moduleSize). Both foreground and background colors must be valid "#RRGGBB" hex strings.
func (*PDFRenderer) Type ¶
func (r *PDFRenderer) Type() string
Type returns the format identifier "pdf".
type PNGRenderer ¶
type PNGRenderer struct{}
PNGRenderer renders QR codes as PNG raster images.
The renderer supports the full range of module styles including rounded rectangles, circles, diamonds, linear gradient fills, and transparency (alpha blending). When a non-square ModuleStyle or gradient is configured, the renderer delegates to the advanced drawing functions in advanced_png.go (DrawModule, DrawRoundedRect, DrawCircle, DrawDiamond, etc.).
For plain square modules with no gradient or transparency, a fast pixel-fill path is used instead.
Example:
r := renderer.NewPNGRenderer()
err := r.Render(ctx, qr, os.Stdout,
renderer.WithWidth(512),
renderer.WithGradient("#4A00E0", "#8E2DE2", 135),
renderer.WithRoundedModules(0.5),
)
func NewPNGRenderer ¶
func NewPNGRenderer() *PNGRenderer
NewPNGRenderer creates a new PNGRenderer. The returned renderer is stateless and safe for concurrent use.
func (*PNGRenderer) ContentType ¶
func (r *PNGRenderer) ContentType() string
ContentType returns the MIME type "image/png".
func (*PNGRenderer) Render ¶
func (r *PNGRenderer) Render(_ context.Context, qr *encoding.QRCode, w io.Writer, opts ...RenderOption) error
Render writes the QR code as a PNG image to w using the given render options.
The output dimensions are determined by the Width option: a pixel scale factor is computed as Width / (qr.Size + 2*QuietZone) and applied uniformly to all modules. The resulting image is always square.
When ModuleStyle is set with a non-square shape, gradient, or transparency, the advanced drawing path is activated. Otherwise, a fast path fills square modules directly.
func (*PNGRenderer) Type ¶
func (r *PNGRenderer) Type() string
Type returns the format identifier "png".
type RenderConfig ¶
type RenderConfig struct {
// Width is the target output width in pixels.
// For raster formats (PNG), this directly controls image dimensions.
// A scale factor is computed from Width and the total module count
// (including quiet zones) to determine the per-module pixel size.
Width int
// Height is the target output height in pixels.
// When set to the same value as Width, the QR code is rendered square.
Height int
// ForegroundColor is the module (dark segment) color as a 7-character
// hex string in "#RRGGBB" format. Defaults to "#000000" (black).
ForegroundColor string
// BackgroundColor is the background color as a 7-character hex string
// in "#RRGGBB" format. Defaults to "#FFFFFF" (white).
BackgroundColor string
// QuietZone is the number of quiet-zone (margin) modules surrounding
// the QR code on all sides. The QR code specification requires at
// least 4 quiet-zone modules for reliable scanning. Defaults to 4.
QuietZone int
// BorderWidth is an extra border in pixels added outside the quiet zone.
// This is used by some renderers (e.g., PDF) to add visual padding.
BorderWidth int
// ModuleStyle controls the visual appearance of individual QR code modules,
// including shape (square, rounded, circle, diamond), gradient fills,
// and transparency. A nil value means default square modules with no
// gradient and full opacity.
ModuleStyle *ModuleStyle
}
RenderConfig holds all parameters that control QR code rendering.
Use ApplyOptions to construct a RenderConfig from defaults with functional options, or call DefaultRenderConfig and modify fields directly. Typical users should prefer the RenderOption pattern.
Example:
cfg := renderer.ApplyOptions(
renderer.WithWidth(512),
renderer.WithForegroundColor("#1A1A2E"),
renderer.WithBackgroundColor("#F0F0F0"),
)
func ApplyOptions ¶
func ApplyOptions(opts ...RenderOption) *RenderConfig
ApplyOptions creates a RenderConfig from DefaultRenderConfig and applies each of the given RenderOption functions in order. This is the recommended way to build a RenderConfig.
Example:
cfg := renderer.ApplyOptions(
renderer.WithWidth(512),
renderer.WithQuietZone(2),
renderer.WithGradient("#FF0000", "#0000FF", 45),
)
func DefaultRenderConfig ¶
func DefaultRenderConfig() *RenderConfig
DefaultRenderConfig returns a RenderConfig with sensible defaults:
- Width: 256, Height: 256
- ForegroundColor: "#000000"
- BackgroundColor: "#FFFFFF"
- QuietZone: 4 (per QR specification)
- BorderWidth: 0
- ModuleStyle: nil (plain square modules)
type RenderOption ¶
type RenderOption func(*RenderConfig)
RenderOption is a functional option that modifies a RenderConfig at render time.
RenderOption functions are designed to be passed to a renderer's Render method. They are applied in order, so later options override earlier ones for the same field. Options that depend on ModuleStyle (such as WithGradient, WithRoundedModules, WithCircleModules, and WithTransparency) will auto-initialize a default ModuleStyle if one is not already set.
Example usage:
opts := []renderer.RenderOption{
renderer.WithWidth(512),
renderer.WithHeight(512),
renderer.WithQuietZone(2),
}
err := renderer.NewPNGRenderer().Render(ctx, qr, os.Stdout, opts...)
func WithBackgroundColor ¶
func WithBackgroundColor(color string) RenderOption
WithBackgroundColor sets the background color as a hex string. The color must be in "#RRGGBB" format, for example "#F5F5F5".
func WithBorderWidth ¶
func WithBorderWidth(bw int) RenderOption
WithBorderWidth sets the extra border width in pixels outside the quiet zone. This is primarily used by PDF rendering to add visual padding.
func WithCircleModules ¶
func WithCircleModules() RenderOption
WithCircleModules sets the module shape to circles. Each module is rendered as a circle inscribed within its cell. If a ModuleStyle has not been set by a previous option, a default one is initialized automatically.
func WithForegroundColor ¶
func WithForegroundColor(color string) RenderOption
WithForegroundColor sets the foreground (module) color as a hex string. The color must be in "#RRGGBB" format, for example "#FF5733".
func WithGradient ¶
func WithGradient(startColor, endColor string, angle float64) RenderOption
WithGradient enables a linear gradient fill from startColor to endColor at the given angle. Colors must be in "#RRGGBB" format. The angle is measured in degrees clockwise from the positive x-axis (0° = left-to-right, 90° = top-to-bottom).
If a ModuleStyle has not been set by a previous option, a default one is initialized automatically.
Example:
err := r.Render(ctx, qr, os.Stdout,
renderer.WithGradient("#4A00E0", "#8E2DE2", 135),
)
func WithHeight ¶
func WithHeight(h int) RenderOption
WithHeight sets the target output height in pixels. For square QR codes, this should typically match the Width.
func WithModuleStyle ¶
func WithModuleStyle(style *ModuleStyle) RenderOption
WithModuleStyle sets the module style for rendering. Pass a fully constructed ModuleStyle to control shape, gradient, and transparency. This option overrides any previous ModuleStyle configuration.
Example:
style := &renderer.ModuleStyle{Shape: "circle"}
err := r.Render(ctx, qr, os.Stdout, renderer.WithModuleStyle(style))
func WithQuietZone ¶
func WithQuietZone(qz int) RenderOption
WithQuietZone sets the number of quiet-zone (margin) modules around the QR code. The quiet zone is required for reliable scanner recognition; the QR specification mandates at least 4 modules. Increasing this value adds more whitespace around the code.
func WithRoundedModules ¶
func WithRoundedModules(roundness float64) RenderOption
WithRoundedModules sets the module shape to rounded rectangles with the given roundness. The roundness value controls the corner radius as a fraction of the module size (0.0 = sharp square, 1.0 = circle). If a ModuleStyle has not been set by a previous option, a default one is initialized automatically.
Example:
err := r.Render(ctx, qr, os.Stdout,
renderer.WithRoundedModules(0.5),
)
func WithTransparency ¶
func WithTransparency(alpha float64) RenderOption
WithTransparency sets the module opacity (alpha) value. A value of 1.0 is fully opaque and 0.0 is fully transparent. If a ModuleStyle has not been set by a previous option, a default one is initialized automatically.
func WithWidth ¶
func WithWidth(w int) RenderOption
WithWidth sets the target output width in pixels. The per-module scale is automatically computed from this value and the total module count (QR matrix size + 2 × quiet zone).
type SVGRenderer ¶
type SVGRenderer struct{}
SVGRenderer renders QR codes as SVG (Scalable Vector Graphics) documents.
The renderer produces a standalone SVG file with an XML declaration, viewBox, and properly namespaced elements. Module shapes other than "square" (rounded, circle, diamond) are supported via the SVG helper functions in svg_helpers.go. Gradient fills are supported via the SVGGradientDef helper.
SVG output is resolution-independent and ideal for use in web pages, print media, or any context where scaling without quality loss is needed.
Example:
r := renderer.NewSVGRenderer()
err := r.Render(ctx, qr, os.Stdout,
renderer.WithForegroundColor("#1A1A2E"),
renderer.WithBackgroundColor("#F5F5F5"),
)
func NewSVGRenderer ¶
func NewSVGRenderer() *SVGRenderer
NewSVGRenderer creates a new SVGRenderer. The returned renderer is stateless and safe for concurrent use.
func (*SVGRenderer) ContentType ¶
func (r *SVGRenderer) ContentType() string
ContentType returns the MIME type "image/svg+xml".
func (*SVGRenderer) Render ¶
func (r *SVGRenderer) Render(_ context.Context, qr *encoding.QRCode, w io.Writer, opts ...RenderOption) error
Render writes the QR code as an SVG document to w using the given render options.
Each dark module is rendered as an SVG <rect> element positioned within a viewBox that includes the quiet zone. The canvas uses a fixed module size of 10 units. Foreground and background colors are validated as "#RRGGBB" hex strings before rendering.
func (*SVGRenderer) Type ¶
func (r *SVGRenderer) Type() string
Type returns the format identifier "svg".
type TerminalRenderer ¶
type TerminalRenderer struct{}
TerminalRenderer renders QR codes as Unicode block characters suitable for terminal output.
The renderer uses a pair of Unicode block characters per column to represent two rows of modules at once, halving the vertical line count:
██ – both top and bottom modules are dark
▀▀ – top module dark, bottom module light
▄▄ – top module light, bottom module dark
– both modules light (two spaces)
When the foreground or background color differs from the defaults (black/white), ANSI 24-bit true-color escape sequences are automatically applied:
\033[38;2;R;G;Bm – set foreground color \033[48;2;R;G;Bm – set background color \033[0m – reset all attributes
Example:
r := renderer.NewTerminalRenderer()
err := r.Render(ctx, qr, os.Stdout,
renderer.WithForegroundColor("#00FF00"),
renderer.WithBackgroundColor("#000000"),
)
func NewTerminalRenderer ¶
func NewTerminalRenderer() *TerminalRenderer
NewTerminalRenderer creates a new TerminalRenderer. The returned renderer is stateless and safe for concurrent use.
func (*TerminalRenderer) ContentType ¶
func (r *TerminalRenderer) ContentType() string
ContentType returns the MIME type "text/plain".
func (*TerminalRenderer) Render ¶
func (r *TerminalRenderer) Render(_ context.Context, qr *encoding.QRCode, w io.Writer, opts ...RenderOption) error
Render writes the QR code as Unicode block characters to w using the given render options.
The output uses two rows of Unicode block characters per two rows of QR modules. Each column emits two characters (to maintain a roughly square aspect ratio in most terminal fonts). ANSI color codes are prepended when non-default colors are specified.
func (*TerminalRenderer) Type ¶
func (r *TerminalRenderer) Type() string
Type returns the format identifier "terminal".