### Install go-qrcode Source: https://github.com/yeqown/go-qrcode/blob/main/README.md Install the go-qrcode library using the go get command. Ensure you are using the latest version. ```sh go get -u github.com/yeqown/go-qrcode/v2 ``` -------------------------------- ### Quick Start: Generate and Save QR Code Source: https://github.com/yeqown/go-qrcode/blob/main/README.md A basic example demonstrating how to generate a QR code for a given URL and save it as a JPEG file. Ensure the output path is accessible. ```go package main import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, err := qrcode.New("https://github.com/yeqown/go-qrcode") if err != nil { fmt.Printf("could not generate QRCode: %v", err) return } w, err := standard.New("../assets/repo-qrcode.jpeg") if err != nil { fmt.Printf("standard.New failed: %v", err) return } // save file if err = qrc.Save(w); err != nil { fmt.Printf("could not save image: %v", err) } } ``` -------------------------------- ### Setup go-qrcode WebAssembly Source: https://github.com/yeqown/go-qrcode/blob/main/example/webassembly/README.md Copy the necessary WebAssembly execution script and the go-qrcode WASM binary to your project directory. Then, serve the directory using a local HTTP server to access the demo in a browser. ```bash cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" . cp "$PATH/go-qrcode/wasm/com.github.yeqown.goqrcode.wasm" . # then serve the index.html in browser python3 -m http.server ``` -------------------------------- ### Initialize and Run WebAssembly Module Source: https://github.com/yeqown/go-qrcode/blob/main/example/webassembly/index.html Instantiates a WebAssembly module compiled from Go and runs its main function. This is a one-time setup for the WebAssembly environment. ```javascript let option = { encodeVersion: 0, encodeMode: 2, encodeECLevel: "Q", outputBgColor: "#123123", outputBgTransparent: true, outputQrColor: "#666666", outputQrWidth: 20, outputCircleShape: true, outputImageEncoder: "png", outputMargin: 20, } run const go = new Go(); WebAssembly.instantiateStreaming(fetch("com.github.yeqown.goqrcode.wasm"), go.importObject).then( result => { go.run(result.instance) } ); ``` -------------------------------- ### Example: Vertical Stripes with Rounded Finders Source: https://context7.com/yeqown/go-qrcode/llms.txt Demonstrates using `shapes.Assemble` with a specific block preset (`VStripeBlock`) and a finder preset (`RoundedFinder`). This example configures the output writer for PNG format and custom shape. ```go // Available block draw functions: shapes.LiquidBlock() // fluid, blob-like connections between adjacent modules shapes.HStripeBlock(0.85) // horizontal stripe connectors shapes.VStripeBlock(0.85) // vertical stripe connectors shapes.ChainBlock() // narrow chain-link connectors in all 4 directions shapes.HChainBlock() // horizontal-only chain-link shapes.VChainBlock() // vertical-only chain-link shapes.SquareBlocks(0.8) // centered square at 80% cell size shapes.CircleBlocks(0.8) // centered circle at 80% radius // Example: vertical stripes with rounded finders shape := shapes.Assemble(shapes.RoundedFinder(), shapes.VStripeBlock(0.9)) w, _ := standard.New("vstripe.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT), standard.WithCustomShape(shape), ) ``` -------------------------------- ### Run QR Code Generation Example Source: https://github.com/yeqown/go-qrcode/blob/main/example/with-minimum-version/README.md Execute the Go program to generate QR code images. This command will produce two files: one with the minimum version constraint and another with automatic version selection. ```bash go run main.go ``` -------------------------------- ### Custom Writer Pseudocode Example Source: https://github.com/yeqown/go-qrcode/blob/main/writer/README.md Illustrates how to implement a custom QR code writer. It outlines the process of iterating through the matrix and drawing blocks based on their state, mapping states to colors. ```pseudocode // define your own writer structure to implement `Writer` interface. object writer {}; writer.Write(matrix.Matrix): // these should be `IMAGE` stream controller, it receives matrix // it decide how to print the image. object paint; // set use BLACK, unset use WHITE. Or provides matrix.State to colors mapping // so that you can control QR Image output intensively. foreach row in matrix: foreach column in row: if column.State in [StateFalse]: // paint a WHITE square block paint.draw(x, y, WHITE); else: // paint a BLACK square block, paint.draw(x, y, BLACK); // loop end; // output paint; ``` -------------------------------- ### Custom Writer for HTTP Response Source: https://context7.com/yeqown/go-qrcode/llms.txt Implement the `qrcode.Writer` interface to write QR codes to custom destinations like HTTP responses. This example uses a `bytes.Buffer` to generate a PNG image served via HTTP. ```go package main import ( "bytes" "io" "net/http" qrcode "github.com/yeqown/go-qrcode/v2" stdw "github.com/yeqown/go-qrcode/writer/standard" ) type nopCloser struct{ io.Writer } func (nopCloser) Close() error { return nil } func qrHandler(w http.ResponseWriter, r *http.Request) { content := r.URL.Query().Get("data") qrc, err := qrcode.New(content) if err != nil { http.Error(w, err.Error(), 400) return } buf := new(bytes.Buffer) writer := stdw.NewWithWriter(nopCloser{buf}, stdw.WithBuiltinImageEncoder(stdw.PNG_FORMAT), stdw.WithQRWidth(10), ) if err = qrc.Save(writer); err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "image/png") w.Write(buf.Bytes()) } func main() { http.HandleFunc("/qr", qrHandler) http.ListenAndServe(":8080", nil) // GET http://localhost:8080/qr?data=hello → PNG QR code image } ``` -------------------------------- ### Implement Custom Circle Shape for QR Code Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/how-to-use-custom-shape.md This example defines a `smallerCircle` struct that implements the `IShape` interface to draw circular QR code modules. It ensures finder patterns are drawn with a full radius for recognition. ```go func newShape(radiusPercent float64) qrcode.IShape { return &smallerCircle{smallerPercent: radiusPercent} } // smallerCircle use smaller circle to qrcode. type smallerCircle struct { smallerPercent float64 } func (sc *smallerCircle) DrawFinder(ctx *qrcode.DrawContext) { // use normal radius to draw finder for that qrcode image can be recognized. backup := sc.smallerPercent sc.smallerPercent = 1.0 sc.Draw(ctx) sc.smallerPercent = backup } func (sc *smallerCircle) Draw(ctx *qrcode.DrawContext) { w, h := ctx.Edge() upperLeft := ctx.UpperLeft() color := ctx.Color() // choose a proper radius values radius := w / 2 r2 := h / 2 if r2 <= radius { radius = r2 } // 80 percent smaller radius = int(float64(radius) * sc.smallerPercent) cx, cy := upperLeft.X+w/2, upperLeft.Y+h/2 // get center point ctx.DrawCircle(float64(cx), float64(cy), float64(radius)) ctx.SetColor(color) ctx.Fill() } ``` -------------------------------- ### Compose Custom QR Code Shapes Source: https://context7.com/yeqown/go-qrcode/llms.txt Assembles custom finder and data block drawing functions into a complete QR code shape. This example combines rounded finders with liquid data blocks. Ensure the output file format is specified if not using default. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" "github.com/yeqown/go-qrcode/writer/standard/shapes" ) func main() { // Combine built-in presets: rounded finder + liquid data blocks shape := shapes.Assemble(shapes.RoundedFinder(), shapes.LiquidBlock()) qrc, _ := qrcode.New("https://github.com/yeqown/go-qrcode") w, err := standard.New("liquid.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT), standard.WithCustomShape(shape), standard.WithQRWidth(16), ) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) } ``` -------------------------------- ### Initialize and Save with Compressed Writer Source: https://github.com/yeqown/go-qrcode/blob/main/writer/compressed/README.md Configure and use the compressed writer to save a QR code. Adjust padding and block size for desired output. Ensure error handling for writer creation and saving. ```go option := compressed.Option{ Padding: 4, // padding pixels around the qr code. BlockSize: 1, // block pixels which represents a bit data. } w, err := compressed.New(name, &option) if err != nil { panic(err) } if err := qrc.Save(w); err != nil { panic(err) } ``` -------------------------------- ### Create QR Code Writer with Options Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/README.md Use this to create a new QR code writer, either for a file or an io.WriteCloser, with customizable options like background and foreground colors. ```go options := []standard.ImageOption{ standard.WithBgColorRGBHex("#ffffff"), standard.WithFgColorRGBHex("#000000"), // more ... } // New will create file automatically. writer, err := standard.New("filename", options...) // or use io.WriteCloser var w io.WriterCloser writer2, err := standard.NewWith(w, options...) ``` -------------------------------- ### Build WASM Binary (Bash) Source: https://github.com/yeqown/go-qrcode/blob/main/cmd/wasm/README.md This command builds the WebAssembly binary for go-qrcode. Ensure you are in the correct directory and set the appropriate environment variables for the target operating system and architecture. ```bash cd $PATH/to/go-qrcode/cmd/wasm GOOS=js GOARCH=wasm go build -o com.github.yeqown.goqrcode.wasm . ``` -------------------------------- ### Set Background and Foreground Colors Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithBgColor` and `WithFgColor` to set the background and QR module colors respectively. Colors can be specified using `color.RGBA` or `WithBgColorRGBHex`/`WithFgColorRGBHex`. ```go package main import ( "image/color" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, _ := qrcode.New("https://example.com") w, err := standard.New("colored-bg.jpeg", standard.WithBgColor(color.RGBA{R: 124, G: 252, B: 0, A: 255}), // lime background standard.WithFgColor(color.RGBA{R: 135, G: 206, B: 235, A: 255}), // sky-blue foreground ) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) // Output: colored-bg.jpeg with lime bg and sky-blue QR modules } ``` ```go w, err := standard.New("custom-fg.jpeg", standard.WithFgColorRGBHex("#1a1aff"), // deep blue modules standard.WithBgColorRGBHex("#fffde7"), // cream background ) ``` -------------------------------- ### Generate QR Code to File Source: https://github.com/yeqown/go-qrcode/blob/main/writer/file/README.md Use the file writer to create a QR code and save it to a file-like object. Ensure necessary packages are imported. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/file" ) func main() { qrc, _ := qrcode.New("with_file_writer") w := file.New(os.Stdout) if err := qrc.Save(w); err != nil { panic(err) } } ``` -------------------------------- ### Choose JPEG or PNG Output Format Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithBuiltinImageEncoder` to select between JPEG (default, smaller) and PNG (lossless, supports transparency). `WithBgTransparent()` can only be used with PNG format. ```go w, err := standard.New("qr.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT), standard.WithBgTransparent(), // only works with PNG ) ``` -------------------------------- ### Create Standard Image Writer Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `standard.New` to create a writer that saves to a file, or `standard.NewWithWriter` to use any `io.WriteCloser` for streaming output. ```go // Write to file w, err := standard.New("qr.jpeg") // Write to custom stream w2 := standard.NewWithWriter(myWriteCloser, standard.WithBuiltinImageEncoder(standard.PNG_FORMAT)) ``` -------------------------------- ### QR Code CLI Help Source: https://github.com/yeqown/go-qrcode/blob/main/cmd/qrcode/README.md Displays the help information for the qrcode CLI application, outlining available commands, options, and usage. ```sh $ qrcode -h NAME: qrcode - qrcode [options] [source text] USAGE: qrcode [global options] command [command options] [arguments...] VERSION: v2.0.0-beta DESCRIPTION: QR code generator AUTHOR: yeqown COMMANDS: help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --terminal --terminal (default: false) --output value, -o value --output= (default: qrcode.jpg) --block value, -s value --block= (default: 5) --borders value, -b value --borders= (default: 0,0,0,0) --circle --circle (default: false) --help, -h show help (default: false) --version, -v print the version (default: false) COPYRIGHT: Copyright (c) 2018 yeqown Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ``` -------------------------------- ### Generate a Small Paletted PNG with Compressed Writer Source: https://context7.com/yeqown/go-qrcode/llms.txt Produces a minimal 2-color paletted PNG using best-compression, ideal for bandwidth-constrained contexts. Configure padding and block size using the Option struct. ```go package main import ( "fmt" qrcode "github.com/yeqown/go-qrcode/v2" compw "github.com/yeqown/go-qrcode/writer/compressed" ) func main() { qrc, err := qrcode.New("https://example.com") if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } w, err := compw.New("small.png", &compw.Option{ Padding: 2, // pixels of quiet zone BlockSize: 4, // pixels per QR module }) if err != nil { panic(err) } if err = qrc.Save(w); err != nil { fmt.Printf("could not save compressed QR: %v\n", err) } // Output: small.png — a tiny, best-compression paletted PNG } ``` -------------------------------- ### Set Transparent Background Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithBgTransparent` to make the QR code background fully transparent. This option requires the output format to be PNG. ```go w, err := standard.New("transparent.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT), standard.WithBgTransparent(), ) ``` -------------------------------- ### Generate QR Code with Minimum Version 9 Source: https://github.com/yeqown/go-qrcode/blob/main/example/with-minimum-version/README.md Use the `WithMinimumVersion` option when creating a QR code to enforce a minimum size. This ensures the QR code will be at least version 9, even if the content could fit in a smaller version. Error correction level is also specified. ```go qrc, err := qrcode.NewWith("your-text-here", qrcode.WithMinimumVersion(9), qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionQuart), ) ``` -------------------------------- ### WithBuiltinImageEncoder - JPEG or PNG Output Source: https://context7.com/yeqown/go-qrcode/llms.txt Allows selection between JPEG (default, smaller file size) and PNG (lossless, supports transparency) output formats for the generated QR code image. ```APIDOC ### `WithBuiltinImageEncoder` — Choose JPEG or PNG output format Switches the output encoder between JPEG (default, smaller) and PNG (lossless, supports transparency). ### Example Usage: ```go import "github.com/yeqown/go-qrcode/writer/standard" w, err := standard.New("qr.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT), standard.WithBgTransparent(), // only works with PNG ) ``` ``` -------------------------------- ### Print QR Code to Terminal Source: https://context7.com/yeqown/go-qrcode/llms.txt Renders a QR code directly in the terminal using the `termbox` library. The program will block execution until any key is pressed. Ensure proper error handling for QR code generation and terminal output. ```go package main import ( "fmt" qrcode "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/terminal" ) func main() { qrc, err := qrcode.New("https://example.com") if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } w := terminal.New() defer w.Close() if err = qrc.Save(w); err != nil { fmt.Printf("could not print to terminal: %v\n", err) } // The terminal shows the QR code; press any key to exit. } ``` -------------------------------- ### Generate QR Code to Terminal Source: https://github.com/yeqown/go-qrcode/blob/main/writer/terminal/README.md Use the Terminal Writer to save a QR code directly to the console. Ensure the necessary packages are imported. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/terminal" ) func main() { qrc, _ := qrcode.New("withTerminalWriter") w := terminal.New() if err := qrc.Save(w); err != nil { panic(err) } } ``` -------------------------------- ### Create QR Code with Custom Encoding Options Source: https://context7.com/yeqown/go-qrcode/llms.txt Generates a QR code with explicit control over encoding mode, error correction level, and minimum QR version. Prints the QR code's dimension and saves it as a PNG image. ```go package main import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, err := qrcode.NewWith( "HELLO WORLD 2025", qrcode.WithEncodingMode(qrcode.EncModeAlphanumeric), qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionHighest), // 30% recovery qrcode.WithMinimumVersion(5), // at least version 5 even if data fits smaller ) if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } fmt.Printf("QR dimension: %d x %d\n", qrc.Dimension(), qrc.Dimension()) // Output: QR dimension: 37 x 37 (version 5 = 4*5+17) w, err := standard.New("alphanumeric.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT)) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) } ``` -------------------------------- ### Generate QR Code with Halftone Source: https://github.com/yeqown/go-qrcode/blob/main/example/with-halftone/README.md Generates a QR code with a specified halftone image and QR code width. Supports an option for a transparent background. ```go var ( transparent = flag.Bool("transparent", false, "set background to transparent") ) func main() { qrc, err := qrcode.New("https://github.com/yeqown/go-qrcode") if err != nil { panic(err) } options := []standard.ImageOption{ standard.WithHalftone("./test.jpeg"), standard.WithQRWidth(21), } filename := "./halftone-qr.png" if *transparent { options = append( options, standard.WithBuiltinImageEncoder(standard.PNG_FORMAT), standard.WithBgTransparent(), ) filename = "./halftone-qr-transparent.png" } w0, err := standard.New(filename, options...) handleErr(err) err = qrc.Save(w0) handleErr(err) } ``` -------------------------------- ### Apply Linear Gradient to QR Modules Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithFgGradient` to apply a multi-stop linear gradient to the QR module pixels. The gradient angle is specified in degrees. ```go package main import ( "image/color" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, _ := qrcode.NewWith("https://example.com", qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionLow)) gradient := standard.NewGradient(45, standard.ColorStop{T: 0.0, Color: color.RGBA{R: 255, A: 255}}, // red standard.ColorStop{T: 0.5, Color: color.RGBA{G: 255, A: 255}}, // green standard.ColorStop{T: 1.0, Color: color.RGBA{B: 255, A: 255}}, // blue ) w, err := standard.New("gradient.jpeg", standard.WithFgGradient(gradient)) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) // Output: gradient.jpeg with red→green→blue diagonal gradient on QR modules } ``` -------------------------------- ### Apply Halftone Effect to QR Code Source: https://context7.com/yeqown/go-qrcode/llms.txt Renders QR code modules as a halftone of a source image for artistic effects. Use larger QR block sizes (`WithQRWidth`) for a better halftone appearance. The background image must exist at the specified path. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, _ := qrcode.New("https://example.com") w, err := standard.New("halftone.jpeg", standard.WithHalftone("./background.png"), // image to use as halftone pattern standard.WithQRWidth(21), // larger blocks for better halftone effect ) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) // Output: halftone.jpeg where QR data cells display the halftone of background.png } ``` -------------------------------- ### Generate QR Codes with Different Encoding Modes Source: https://context7.com/yeqown/go-qrcode/llms.txt Demonstrates generating QR codes using various explicit encoding modes (Numeric, Alphanumeric, Kanji, Byte) and saving them to different JPEG files. Uses medium error correction level. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { // EncModeAuto — auto-detect (default) // EncModeNumeric — digits 0-9 only // EncModeAlphanumeric — 0-9, A-Z and $ % * + - . / : space // EncModeKanji — Shift JIS CJK characters // EncModeByte — arbitrary UTF-8 / binary examples := []struct { content string mode qrcode.EncodeOption file string }{ {"0123456789", qrcode.WithEncodingMode(qrcode.EncModeNumeric), "numeric.jpeg"}, {"HELLO WORLD", qrcode.WithEncodingMode(qrcode.EncModeAlphanumeric), "alpha.jpeg"}, {"こんにちは", qrcode.WithEncodingMode(qrcode.EncModeKanji), "kanji.jpeg"}, {"Hello, 世界!", qrcode.WithEncodingMode(qrcode.EncModeByte), "byte.jpeg"}, } for _, ex := range examples { qrc, err := qrcode.NewWith(ex.content, ex.mode, qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionMedium)) if err != nil { panic(err) } w, _ := standard.New(ex.file) defer w.Close() _ = qrc.Save(w) } } ``` -------------------------------- ### Implement Fully Custom QR Module Shape Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithCustomShape` to define a completely custom shape for QR modules and finder patterns by implementing the `standard.IShape` interface. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) // smallDot renders each module as a small dot (70% of cell size). type smallDot struct{} func (s smallDot) Draw(ctx *standard.DrawContext) { w, h := ctx.Edge() x, y := ctx.UpperLeft() cx, cy := x+float64(w)/2, y+float64(h)/2 ctx.DrawCircle(cx, cy, float64(w)/2*0.7) ctx.SetColor(ctx.Color()) ctx.Fill() } func (s smallDot) DrawFinder(ctx *standard.DrawContext) { s.Draw(ctx) } func main() { qrc, _ := qrcode.New("custom shape example") w, err := standard.New("small-dots.jpeg", standard.WithCustomShape(smallDot{})) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) } ``` -------------------------------- ### qrcode.NewWith Source: https://context7.com/yeqown/go-qrcode/llms.txt Creates a *QRCode with explicit control over error correction level, encoding mode, fixed QR version, and minimum QR version. All options are composable via variadic EncodeOption arguments. ```APIDOC ## qrcode.NewWith ### Description Creates a `*QRCode` with explicit control over error correction level, encoding mode, fixed QR version, and minimum QR version. All options are composable via variadic `EncodeOption` arguments. ### Method `qrcode.NewWith(content string | []byte, options ...qrcode.EncodeOption)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (EncodeOption) - `qrcode.WithEncodingMode(mode qrcode.EncodingMode)`: Sets the encoding mode (e.g., `qrcode.EncModeAlphanumeric`). - `qrcode.WithErrorCorrectionLevel(level qrcode.ErrorCorrectionLevel)`: Sets the error correction level (e.g., `qrcode.ErrorCorrectionHighest`). - `qrcode.WithMinimumVersion(version int)`: Sets the minimum QR version. ### Request Example ```go package main import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, err := qrcode.NewWith( "HELLO WORLD 2025", qrcode.WithEncodingMode(qrcode.EncModeAlphanumeric), qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionHighest), // 30% recovery qrcode.WithMinimumVersion(5), // at least version 5 even if data fits smaller ) if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } fmt.Printf("QR dimension: %d x %d\n", qrc.Dimension(), qrc.Dimension()) // Output: QR dimension: 37 x 37 (version 5 = 4*5+17) w, err := standard.New("alphanumeric.png", standard.WithBuiltinImageEncoder(standard.PNG_FORMAT)) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) } ``` ### Response #### Success Response (200) Returns a `*QRCode` object and an error if generation fails. The `Dimension()` method can be called on the returned `*QRCode` object. #### Response Example ```go // No direct response example for the function itself, but the QR code's dimension can be accessed. // fmt.Printf("QR dimension: %d x %d\n", qrc.Dimension(), qrc.Dimension()) ``` ``` -------------------------------- ### Set Minimum QR Code Version with `WithMinimumVersion` Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithMinimumVersion` to ensure the generated QR code is at least a specified version. This is helpful for maintaining a consistent physical size across different QR codes, even if their content could fit in a smaller version. ```go package main import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { // "Hi" would normally fit in version 1, but we need at least version 9 qrc, err := qrcode.NewWith("Hi", qrcode.WithMinimumVersion(9), qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionQuart), ) if err != nil { panic(fmt.Sprintf("could not generate QRCode: %v", err)) } fmt.Printf("Dimension: %d (expected %d for version 9)\n", qrc.Dimension(), 9*4+17) // Output: Dimension: 53 (expected 53 for version 9) w, _ := standard.New("min-version.png", standard.WithQRWidth(20)) defer w.Close() _ = qrc.Save(w) } ``` -------------------------------- ### QR Code Halftone Option Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/README.md Apply a halftone effect to the QR code using an image file. ```go // WithHalftone ... func WithHalftone(path string) ImageOption ``` -------------------------------- ### Standard Writer - File and Stream Output Source: https://context7.com/yeqown/go-qrcode/llms.txt Provides standard writer implementations for saving QR codes to files or custom streams. `standard.New` creates a writer for a file, while `standard.NewWithWriter` accepts any `io.WriteCloser`. ```APIDOC ## Standard Writer — `github.com/yeqown/go-qrcode/writer/standard` ### `standard.New` / `standard.NewWithWriter` — Create an image writer `New` opens a file and returns a writer; `NewWithWriter` accepts any `io.WriteCloser` for streaming use cases. ### Example Usage: ```go import "github.com/yeqown/go-qrcode/writer/standard" // Write to file w, err := standard.New("qr.jpeg") // Write to custom stream // Assuming myWriteCloser implements io.WriteCloser // w2 := standard.NewWithWriter(myWriteCloser, standard.WithBuiltinImageEncoder(standard.PNG_FORMAT)) ``` ``` -------------------------------- ### Generate a small paletted PNG Source: https://context7.com/yeqown/go-qrcode/llms.txt Produces a minimal 2-color paletted PNG using best-compression, ideal for bandwidth-constrained contexts. ```APIDOC ## Compressed Writer — `github.com/yeqown/go-qrcode/writer/compressed` ### `compressed.New` — Generate a small paletted PNG ### Description Produces a minimal 2-color paletted PNG using best-compression, ideal for bandwidth-constrained contexts (e.g., network transfer, embedded devices). ### Method ```go func New(filename string, opt *Option) (*Writer, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters - **filename** (string) - Required - The name of the file to save the PNG to. #### Query Parameters None #### Request Body - **opt** (*Option) - Required - Options for the compressed PNG writer. - **Padding** (int) - Pixels of quiet zone. - **BlockSize** (int) - Pixels per QR module. ### Request Example ```go package main import ( "fmt" qrcode "github.com/yeqown/go-qrcode/v2" compw "github.com/yeqown/go-qrcode/writer/compressed" ) func main() { qrc, err := qrcode.New("https://example.com") if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } w, err := compw.New("small.png", &compw.Option{ Padding: 2, // pixels of quiet zone BlockSize: 4, // pixels per QR module }) if err != nil { panic(err) } if err = qrc.Save(w); err != nil { fmt.Printf("could not save compressed QR: %v\n", err) } // Output: small.png — a tiny, best-compression paletted PNG } ``` ### Response #### Success Response (200) None (writes to file) #### Response Example None ``` -------------------------------- ### Write QR Code as Unicode Block Art to Text File Source: https://context7.com/yeqown/go-qrcode/llms.txt Encodes the QR matrix as Unicode half-block characters and writes to a text file. Ensure the 'filew' package is imported. ```go package main import ( "fmt" "os" qrcode "github.com/yeqown/go-qrcode/v2" filew "github.com/yeqown/go-qrcode/writer/file" ) func main() { qrc, err := qrcode.New("https://example.com") if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } f, err := os.Create("qr.txt") if err != nil { panic(err) } defer f.Close() w := filew.New(f) if err = qrc.Save(w); err != nil { fmt.Printf("could not write text QR: %v\n", err) return } // Output: qr.txt contains the QR code as Unicode block characters } ``` -------------------------------- ### Generate QR Code to File (Default) Source: https://github.com/yeqown/go-qrcode/blob/main/cmd/qrcode/README.md Generates a QR code for the provided text and saves it to a file named 'qrcode.jpg' by default. ```sh # Generate a QR code into file as default qrcode "Hello, World!" ``` -------------------------------- ### Embed Logo in QR Code (JPEG/PNG) Source: https://context7.com/yeqown/go-qrcode/llms.txt Overlays a logo image onto the QR code. Ensure the logo is not too large (default max 1/5th of QR width) and use `ErrorCorrectionHighest` for scannability. The logo file must exist at the specified path. ```go package main import ( "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, err := qrcode.NewWith("https://example.com", qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionHighest), ) if err != nil { panic(err) } w, err := standard.New("logo.jpeg", standard.WithLogoImageFileJPEG("./brand-logo.jpeg"), standard.WithLogoSafeZone(), // clears QR blocks behind the logo standard.WithLogoSizeMultiplier(4), // logo may be up to 1/4 of QR width ) if err != nil { panic(err) } defer w.Close() _ = qrc.Save(w) } ``` -------------------------------- ### Force QR Code Version with `WithVersion` Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithVersion` to fix the QR code to a specific version (1-40), overriding the library's automatic version selection based on content length. This is useful when a precise physical size is needed. ```go qrc, err := qrcode.NewWith( "42", qrcode.WithVersion(10), // force version 10 qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionLow), ) if err != nil { panic(err) } fmt.Println(qrc.Dimension()) // 57 (= 4*10 + 17) ``` -------------------------------- ### Generate QR Code with Custom Shape Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/how-to-use-custom-shape.md This is the main function to generate a QR code using a custom shape. It initializes the QR code with the custom shape and saves the output to a PNG file. ```go func main() { shape := newShape(0.7) qrc, err := qrcode.New("with-custom-shape", qrcode.WithCustomShape(shape)) if err != nil { panic(err) } err = qrc.Save("./smaller.png") if err != nil { panic(err) } } ``` -------------------------------- ### Create QR Code with Default Options Source: https://context7.com/yeqown/go-qrcode/llms.txt Generates a QR code with automatic encoding-mode detection and the default error correction level (Level Q). Saves the QR code as a JPEG image. ```go package main import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, err := qrcode.New("https://github.com/yeqown/go-qrcode") if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } w, err := standard.New("output.jpeg") if err != nil { fmt.Printf("could not create writer: %v\n", err) return } defer w.Close() if err = qrc.Save(w); err != nil { fmt.Printf("could not save image: %v\n", err) return } // Output: output.jpeg written as a JPEG QR code image } ``` -------------------------------- ### Set Padding Around QR Code Source: https://context7.com/yeqown/go-qrcode/llms.txt Use `WithBorderWidth` to control the padding around the QR code. It accepts 1, 2, or 4 integers following CSS-style shorthand for specifying padding on all sides, top/bottom + left/right, or individual sides. ```go // All four sides = 20px w, _ := standard.New("padded.jpeg", standard.WithBorderWidth(20)) ``` ```go // Top/bottom = 10px, left/right = 40px w, _ = standard.New("asymmetric.jpeg", standard.WithBorderWidth(10, 40)) ``` ```go // top=5, right=10, bottom=20, left=30 w, _ = standard.New("css-style.jpeg", standard.WithBorderWidth(5, 10, 20, 30)) ``` -------------------------------- ### Generate QR Code with Custom Options Source: https://github.com/yeqown/go-qrcode/blob/main/cmd/qrcode/README.md Generates a QR code with specified output file, block size, and border dimensions. The unit for block size and borders is pixels. ```sh # Generate a QR code into file with block size and borders (unit: pixel) qrcode -o qrcode.png -s 20 -b 20,20,20,20 -m "Hello, World!" ``` -------------------------------- ### WithMinimumVersion - Set Version Floor Source: https://context7.com/yeqown/go-qrcode/llms.txt Ensures the generated QR code is at least a given version. This is useful when a consistent physical size is required, even if the content could fit in a smaller QR code. ```APIDOC ## `WithMinimumVersion` — Set a version floor Ensures the generated QR code is at least a given version, useful when a consistent physical size is required. ### Example Usage: ```go import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) // ... // "Hi" would normally fit in version 1, but we need at least version 9 qrc, err := qrcode.NewWith("Hi", qrcode.WithMinimumVersion(9), qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionQuart), ) if err != nil { panic(fmt.Sprintf("could not generate QRCode: %v", err)) } fmt.Printf("Dimension: %d (expected %d for version 9)\\n", qrc.Dimension(), 9*4+17) // Output: Dimension: 53 (expected 53 for version 9) w, _ := standard.New("min-version.png", standard.WithQRWidth(20)) def w.Close() _ = qrc.Save(w) ``` ``` -------------------------------- ### QR Code Logo Size and Safe Zone Options Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/README.md Configure the size multiplier and safe zone for a logo embedded within the QR code. ```go // WithLogoSizeMultiplier used in Writer in validLogoImage method to validate logo size func WithLogoSizeMultiplier(multiplier int) // WithLogoSafeZone specify the safe zone of logo image func WithLogoSafeZone() ``` -------------------------------- ### qrcode.New Source: https://context7.com/yeqown/go-qrcode/llms.txt Creates a *QRCode from any string or []byte value using automatic encoding-mode detection and the default error correction level (Level Q, 25% recovery). ```APIDOC ## qrcode.New ### Description Creates a `*QRCode` from any string or `[]byte` value using automatic encoding-mode detection and the default error correction level (Level Q, 25% recovery). ### Method `qrcode.New(content string | []byte)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/yeqown/go-qrcode/v2" "github.com/yeqown/go-qrcode/writer/standard" ) func main() { qrc, err := qrcode.New("https://github.com/yeqown/go-qrcode") if err != nil { fmt.Printf("could not generate QRCode: %v\n", err) return } w, err := standard.New("output.jpeg") if err != nil { fmt.Printf("could not create writer: %v\n", err) return } defer w.Close() if err = qrc.Save(w); err != nil { fmt.Printf("could not save image: %v\n", err) return } // Output: output.jpeg written as a JPEG QR code image } ``` ### Response #### Success Response (200) Returns a `*QRCode` object and an error if generation fails. #### Response Example ```go // No direct response example for the function itself, but the generated QR code is saved to a file. ``` ``` -------------------------------- ### QR Code Gradient Option Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/README.md Apply a linear gradient to the foreground of the QR code. ```go // QR gradient func WithFgGradient(g *LinearGradient) ``` -------------------------------- ### WithVersion - Force QR Version Source: https://context7.com/yeqown/go-qrcode/llms.txt Forces an exact QR version (1–40) for the generated QR code, regardless of how much data the content requires. This is useful when a specific QR code size is needed. ```APIDOC ## `WithVersion` — Fix the QR version Forces an exact QR version (1–40) regardless of how much data the content requires. ### Example Usage: ```go import ( "fmt" "github.com/yeqown/go-qrcode/v2" ) // ... qrc, err := qrcode.NewWith( "42", qrcode.WithVersion(10), // force version 10 qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionLow), ) if err != nil { panic(err) } fmt.Println(qrc.Dimension()) // 57 (= 4*10 + 17) ``` ``` -------------------------------- ### Control QR Module Pixel Size Source: https://context7.com/yeqown/go-qrcode/llms.txt Set the pixel width of each QR module block using `WithQRWidth`. The default value is 20 pixels. ```go w, err := standard.New("large.jpeg", standard.WithQRWidth(30)) // 30×30 px per module ``` -------------------------------- ### Generate QR Code to Terminal Source: https://github.com/yeqown/go-qrcode/blob/main/cmd/qrcode/README.md Generates a QR code for the provided text and displays it directly in the terminal. ```sh # Generate a QR code into terminal qrcode --terminal "Hello, World!" ``` -------------------------------- ### QR Code Writer Interface Definition Source: https://github.com/yeqown/go-qrcode/blob/main/writer/README.md Defines the `Writer` interface for rendering QR code matrices. Implementations should handle writing the QR code image to a stream and closing the stream. ```go package qrcode import "io" // Writer is the interface of a QR code writer, it defines the rule of how to // `print` the code image from matrix. There's built-in writer to output into // file, terminal. type Writer interface { // Write writes the code image into itself stream, such as io.Writer, // terminal output stream, and etc Write(mat matrix.Matrix) error // Close the writer stream if it exists after QRCode.Save() is called. Close() error } ``` -------------------------------- ### QR Code Background Color Options Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/README.md Configure the background color of the QR code. Supports transparent backgrounds or specific colors using color.Color or hex strings. ```go // WithBgTransparent makes the background transparent. func WithBgTransparent() ImageOption {} // WithBgColor background color func WithBgColor(c color.Color) ImageOption {} // WithBgColorRGBHex background color func WithBgColorRGBHex(hex string) ImageOption {} ``` -------------------------------- ### Use Circular QR Modules Source: https://context7.com/yeqown/go-qrcode/llms.txt Replace the default square QR code blocks with filled circles using the `WithCircleShape` option. ```go w, err := standard.New("circles.jpeg", standard.WithCircleShape()) ``` -------------------------------- ### QR Code Block Width Option Source: https://github.com/yeqown/go-qrcode/blob/main/writer/standard/README.md Specify the width of each individual QR code block (module). ```go // WithQRWidth specify width of each qr block func WithQRWidth(width uint8) ImageOption {} ```