Documentation
¶
Overview ¶
Package qrkit generates QR codes (ISO/IEC 18004 Model 2) as images or SVG, with rich styling, using only the Go standard library.
Quick start ¶
qr, err := qrkit.New("https://q.mohamedation.com")
if err != nil {
log.Fatal(err)
}
if err := qr.Save("code.png"); err != nil { // or "code.svg"
log.Fatal(err)
}
Styling ¶
Everything is configured with functional options passed to New:
qr, err := qrkit.New("https://q.mohamedation.com",
qrkit.WithSize(600),
qrkit.WithForeground(color.NRGBA{0x1b, 0x2a, 0x49, 0xff}),
qrkit.WithTransparentBackground(),
qrkit.WithModuleShape(qrkit.ShapeRounded),
qrkit.WithFinderStyle(qrkit.FinderStyle{Shape: qrkit.FinderRounded}),
qrkit.WithLogo(logoImage, qrkit.LogoClip(qrkit.LogoCircle)),
)
Module shapes, finder ("eye") shapes and colours, foreground and background colours (including transparency), module gaps, quiet zone, output size, mask, version range and error-correction level can all be chosen independently.
Logos ¶
WithLogo places an image in the centre. The modules beneath it are removed and the code relies on error correction to stay readable, so the library defaults to the highest recovery level, verifies for every error-correction block that the logo stays within a conservative budget, and automatically moves to a larger symbol version when that is needed. If a logo cannot be placed safely, New returns an error wrapping ErrLogoTooLarge. Always test the final code with real scanners.
Output ¶
A QRCode can be rendered as an image.Image (QRCode.Image), PNG (QRCode.PNG, QRCode.WritePNG), SVG (QRCode.SVG, QRCode.WriteSVG), written to a file (QRCode.Save) or inspected as a boolean matrix (QRCode.Matrix) so that you can render it any way you like.
Concurrency ¶
A QRCode is immutable; all its methods are safe for concurrent use.
Limitations ¶
Supported: versions 1-40, all four error-correction levels, numeric, alphanumeric and byte modes (chosen automatically, one mode per code). Not supported: Kanji mode, ECI headers, structured append, FNC1, Micro QR and rMQR. Text is encoded as UTF-8 bytes, which virtually all modern scanners handle.
Example ¶
package main
import (
"fmt"
"github.com/mohamedation/qrkit"
)
func main() {
qr, err := qrkit.New("https://q.mohamedation.com")
if err != nil {
panic(err)
}
fmt.Printf("version %d, %dx%d modules, level %s\n", qr.Version(), qr.Size(), qr.Size(), qr.RecoveryLevel())
// qr.Save("code.png") writes a PNG; "code.svg" writes an SVG.
Output:
Index ¶
- Constants
- Variables
- type FinderShape
- type FinderStyle
- type LogoOption
- type LogoShape
- type ModuleShape
- type Option
- func WithBackground(col color.Color) Option
- func WithCornerRadius(r float64) Option
- func WithFinderStyle(s FinderStyle) Option
- func WithForeground(col color.Color) Option
- func WithLogo(img image.Image, opts ...LogoOption) Option
- func WithMask(m int) Option
- func WithModuleScale(s float64) Option
- func WithModuleShape(s ModuleShape) Option
- func WithModuleSize(px int) Option
- func WithQuietZone(modules int) Option
- func WithRecoveryLevel(l RecoveryLevel) Option
- func WithSize(px int) Option
- func WithTransparentBackground() Option
- func WithVersion(v int) Option
- func WithVersionRange(min, max int) Option
- type QRCode
- func (q *QRCode) Image() image.Image
- func (q *QRCode) IsDark(x, y int) bool
- func (q *QRCode) Mask() int
- func (q *QRCode) Matrix() [][]bool
- func (q *QRCode) PNG() ([]byte, error)
- func (q *QRCode) RecoveryLevel() RecoveryLevel
- func (q *QRCode) SVG() (string, error)
- func (q *QRCode) Save(path string) error
- func (q *QRCode) Size() int
- func (q *QRCode) Version() int
- func (q *QRCode) WritePNG(w io.Writer) error
- func (q *QRCode) WriteSVG(w io.Writer) error
- type RecoveryLevel
Examples ¶
Constants ¶
const ( MinVersion = 1 MaxVersion = 40 )
Supported symbol versions.
Variables ¶
var ( // ErrEmptyData is returned when the content to encode is empty. ErrEmptyData = errors.New("qrkit: empty content") // ErrDataTooLong is returned when the content does not fit in any // permitted symbol version at the requested recovery level. ErrDataTooLong = errors.New("qrkit: content too long") // ErrInvalidOption is returned when an option has an out-of-range or // otherwise invalid value. ErrInvalidOption = errors.New("qrkit: invalid option") // ErrLogoTooLarge is returned when a logo would cover too much of the // symbol to remain reliably scannable (or would cover structural // patterns such as the finder patterns). ErrLogoTooLarge = errors.New("qrkit: logo too large") )
Sentinel errors returned (possibly wrapped) by this package. Use errors.Is to test for them.
Functions ¶
This section is empty.
Types ¶
type FinderShape ¶
type FinderShape int
FinderShape selects how the three large corner "eyes" are drawn.
const ( // FinderSquare draws classic square finder patterns (the default). FinderSquare FinderShape = iota // FinderRounded draws finder patterns with rounded corners. FinderRounded // FinderCircle draws circular finder patterns. FinderCircle // FinderModules draws finder patterns module by module, using the // selected ModuleShape. FinderModules )
type FinderStyle ¶
type FinderStyle struct {
// Shape of the eyes.
Shape FinderShape
// OuterColor is the colour of the outer 7x7 ring. Nil means the
// foreground colour.
OuterColor color.Color
// InnerColor is the colour of the central 3x3 block. Nil means
// OuterColor if set, otherwise the foreground colour.
InnerColor color.Color
}
FinderStyle customises the finder patterns.
type LogoOption ¶
type LogoOption func(*logoCfg)
LogoOption customises WithLogo.
func LogoAllowUnsafe ¶
func LogoAllowUnsafe() LogoOption
LogoAllowUnsafe disables the error-correction budget check. The code may then be impossible to scan; the finder/timing/format patterns are still protected. Use only if you test the result.
func LogoClip ¶
func LogoClip(s LogoShape) LogoOption
LogoClip sets the logo's clipping/plate shape. Default LogoSquare.
func LogoPadding ¶
func LogoPadding(modules float64) LogoOption
LogoPadding sets the empty margin around the logo, in modules. Default 1.
func LogoPlate ¶
func LogoPlate(col color.Color) LogoOption
LogoPlate paints a solid plate of the given colour behind the logo, which helps logos with transparency stand out on busy or transparent backgrounds.
func LogoScale ¶
func LogoScale(s float64) LogoOption
LogoScale sets the logo's longer side as a fraction of the symbol width, in (0, 0.5]. Default 0.2.
type LogoShape ¶
type LogoShape int
LogoShape is the shape of the logo's clipping mask and backing plate.
type ModuleShape ¶
type ModuleShape int
ModuleShape selects how each dark module is drawn.
const ( // ShapeSquare draws square modules (the standard look). ShapeSquare ModuleShape = iota // ShapeRounded draws squares whose free corners are rounded; adjacent // modules merge into smooth, blob-like shapes. ShapeRounded // ShapeCircle draws each module as a dot. ShapeCircle // ShapeDiamond draws each module as a diamond. ShapeDiamond // ShapeVerticalBars merges vertically adjacent modules into // rounded-end bars. ShapeVerticalBars // ShapeHorizontalBars merges horizontally adjacent modules into // rounded-end bars. ShapeHorizontalBars )
type Option ¶
type Option func(*config)
Option configures New and NewFromBytes.
func WithBackground ¶
WithBackground sets the background colour (default white). The colour may be translucent or fully transparent.
func WithCornerRadius ¶
WithCornerRadius sets the corner radius of ShapeRounded as a fraction of the module size, in [0, 0.5] (default 0.4).
func WithFinderStyle ¶
func WithFinderStyle(s FinderStyle) Option
WithFinderStyle customises the three finder patterns.
func WithForeground ¶
WithForeground sets the colour of the dark modules (default black).
func WithLogo ¶
func WithLogo(img image.Image, opts ...LogoOption) Option
WithLogo places an image in the centre of the code. The modules beneath it are left out, and the recovery level defaults to LevelHigh. See the Logo* options for size, padding and shape. New fails with ErrLogoTooLarge if the logo cannot be placed safely.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"github.com/mohamedation/qrkit"
)
func main() {
// Any image.Image works: decode a PNG/JPEG with image.Decode, or draw one.
logo := image.NewNRGBA(image.Rect(0, 0, 64, 64))
for i := range logo.Pix {
logo.Pix[i] = 0xff
}
qr, err := qrkit.New("https://q.mohamedation.com",
qrkit.WithLogo(logo, qrkit.LogoScale(0.2), qrkit.LogoClip(qrkit.LogoCircle), qrkit.LogoPlate(color.White)),
)
if err != nil {
panic(err)
}
// With a logo the recovery level defaults to H.
fmt.Println(qr.RecoveryLevel())
}
Output: H
func WithMask ¶
WithMask forces a mask pattern (0-7). The default, -1, evaluates all eight and picks the best, as the standard recommends.
func WithModuleScale ¶
WithModuleScale shrinks each module inside its cell; 1 (default) fills the cell completely, 0.8 leaves a small gap. Values in (0, 1].
func WithModuleShape ¶
func WithModuleShape(s ModuleShape) Option
WithModuleShape selects the module shape (default ShapeSquare).
func WithModuleSize ¶
WithModuleSize sets the size of one module in pixels, so the image is (modules + 2*quiet zone) * px wide. Overrides WithSize (last one wins).
func WithQuietZone ¶
WithQuietZone sets the blank border around the symbol, in modules. The standard requires 4 (the default); scanners may need it.
func WithRecoveryLevel ¶
func WithRecoveryLevel(l RecoveryLevel) Option
WithRecoveryLevel sets the error-correction level (default LevelMedium, or LevelHigh when a logo is used and no level was chosen).
func WithSize ¶
WithSize sets the output image size in pixels (default 512). The image is always exactly px x px; modules get the largest whole pixel size that fits and any remainder is added to the quiet zone. SVG output uses it as the width and height attributes.
func WithTransparentBackground ¶
func WithTransparentBackground() Option
WithTransparentBackground makes the background fully transparent.
func WithVersion ¶
WithVersion forces a specific symbol version (1-40). Encoding fails with ErrDataTooLong if the content does not fit.
func WithVersionRange ¶
WithVersionRange restricts automatic version selection to [min, max].
type QRCode ¶
type QRCode struct {
// contains filtered or unexported fields
}
QRCode is an encoded QR code together with its rendering style. A QRCode is immutable and safe for concurrent use.
func New ¶
New encodes content as a QR code. The most compact of the numeric, alphanumeric and byte (UTF-8) modes is chosen automatically, as is the smallest version that fits.
Example (Styled) ¶
package main
import (
"fmt"
"image/color"
"github.com/mohamedation/qrkit"
)
func main() {
qr, err := qrkit.New("https://q.mohamedation.com",
qrkit.WithSize(600),
qrkit.WithForeground(color.NRGBA{0x1b, 0x2a, 0x49, 0xff}),
qrkit.WithTransparentBackground(),
qrkit.WithModuleShape(qrkit.ShapeRounded),
qrkit.WithFinderStyle(qrkit.FinderStyle{
Shape: qrkit.FinderRounded,
OuterColor: color.NRGBA{0xe8, 0x4a, 0x5f, 0xff},
}),
)
if err != nil {
panic(err)
}
b := qr.Image().Bounds()
fmt.Println(b.Dx(), b.Dy())
}
Output: 600 600
func NewFromBytes ¶
NewFromBytes is like New for arbitrary binary data.
func (*QRCode) Image ¶
Image renders the code as a raster image (*image.NRGBA). Edges are anti-aliased and the background is transparent if so configured.
func (*QRCode) IsDark ¶
IsDark reports whether the module at column x, row y is dark. Coordinates outside the symbol (the quiet zone) report false. The logo area is not taken into account; use Matrix for the raw symbol.
func (*QRCode) Matrix ¶
Matrix returns a copy of the module matrix, indexed [row][column], with true for dark modules and no quiet zone.
Example ¶
package main
import (
"fmt"
"github.com/mohamedation/qrkit"
)
func main() {
qr, _ := qrkit.New("HELLO WORLD")
m := qr.Matrix()
// Print the top-left finder pattern's first row.
for x := 0; x < 7; x++ {
if m[0][x] {
fmt.Print("#")
} else {
fmt.Print(".")
}
}
fmt.Println()
}
Output: #######
func (*QRCode) RecoveryLevel ¶
func (q *QRCode) RecoveryLevel() RecoveryLevel
RecoveryLevel returns the error-correction level actually used.
func (*QRCode) SVG ¶
SVG returns the code as a standalone SVG document. SVG output is resolution independent; a logo is embedded as a PNG data URI.
func (*QRCode) Save ¶
Save writes the code to a file; the format is chosen by the extension (".png" or ".svg", case-insensitive). The destination is replaced only after a successful write, so a failure does not leave a partial file.
type RecoveryLevel ¶
type RecoveryLevel int
RecoveryLevel is the error-correction level of a QR code. Higher levels tolerate more damage (or a larger logo) at the cost of a denser symbol.
const ( // LevelLow recovers roughly 7% of the codewords. LevelLow RecoveryLevel = iota // LevelMedium recovers roughly 15% of the codewords. It is the default. LevelMedium // LevelQuartile recovers roughly 25% of the codewords. LevelQuartile // LevelHigh recovers roughly 30% of the codewords. It is the default // when a logo is used. LevelHigh )
func (RecoveryLevel) String ¶
func (l RecoveryLevel) String() string
String returns "L", "M", "Q" or "H".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
qrkit
command
Command qrkit generates QR codes from the command line.
|
Command qrkit generates QR codes from the command line. |
|
examples
|
|
|
gallery
command
Command gallery renders a set of sample QR codes demonstrating the styling options of qrkit.
|
Command gallery renders a set of sample QR codes demonstrating the styling options of qrkit. |




