preface
Life can not avoid the use of TWO-DIMENSIONAL code application scenarios, so how do we use go language to dynamically generate two-dimensional code
When programming in Go, it is very convenient to generate arbitrary qr codes because we have the go-Qrcode library. The library’s source code is hosted on Github and can be downloaded at github.com/skip2/go-qr…
Simple version of
package main
import "github.com/skip2/go-qrcode"
func main(a) {
qrcode.WriteFile("http://www.codesuger.com/",qrcode.Medium,256."./blog_qrcode.png")}Copy the code
The WriteFile function is prototyped as follows:
- Content Indicates the content of the QR code to be generated. It can be any string.
- Level indicates the fault tolerance level of the TWO-DIMENSIONAL code. The value can be Low, Medium, High, or Highest.
- Size indicates the width and height of the generated image, in pixels.
- Filename indicates the path of the generated filename.
In the current directory, a 256*256 QR code is generated. After scanning, you can see the content is www.codesuger.com/
Generate qr code image bytes
Sometimes we don’t want to directly generate a PNG file storage, we want to do some processing for PNG images, such as scaling, rotation, or network transfer, etc. Based on this, we can use the Encode function to generate a byte stream of PNG images, so that we can do various processing.
func Encode(content string, level RecoveryLevel, size int) ([]byte, error)
Copy the code
The usage is similar to that of the WriteFile function, except that it returns an array of [] bytes that can be processed.
Custom QR code
In addition to the above two shortcuts, the library also provides us with ways to customize the TWO-DIMENSIONAL code, for example, we can customize the two-dimensional code foreground and background color. Qrcode. New function can return a * qrcode, we can set the * qrcode, to achieve the two-dimensional code customization.
For example, we set the background color of green, white foreground color of the TWO-DIMENSIONAL code
package main
import (
"github.com/skip2/go-qrcode"
"image/color"
"log"
)
func main(a) {
qr , err := qrcode.New("http://www.codesuger.com/",qrcode.Medium)
iferr ! =nil {
log.Fatal(err)
}else {
qr.BackgroundColor = color.RGBA{50.205.50.255}
qr.ForegroundColor = color.White
qr.WriteFile(256."./zidingy.png")}}Copy the code
If you have any questions, please leave a comment below
—- people really should cherish everything in front of them — even if you have been tired of seeing these things, maybe one day there will be no