上代码
package main
import (
"bytes"
"encoding/base64"
"fmt"
"github.com/nfnt/resize"
"github.com/skip2/go-qrcode"
"golang.org/x/image/draw"
"image"
_ "image/jpeg"
"image/png"
"os"
)
// CreateQrCodeBs64WithLogo 带logo的二维码图片生成 content-二维码内容 size-像素单位 logoPath-logo文件路径
func CreateQrCodeBs64WithLogo(content, logoPath, outPath string, size int) (err error, data string) {
code, err := qrcode.New(content, qrcode.High)
if err != nil {
return
}
//code.DisableBorder = true
//设置文件大小并创建画板
qrcodeImg := code.Image(size)
outImg := image.NewRGBA(qrcodeImg.Bounds())
//读取logo文件
logoFile, err := os.Open(logoPath)
if err != nil {
return
}
logoImg, _, err := image.Decode(logoFile)
logoImg = resize.Resize(uint(size/5), 0, logoImg, resize.Lanczos3)
// 添加边框
// 图片到边框距离
pic2FramePadding := logoImg.Bounds().Dx() / 10
// 新建一个边框图层
transparentImg := image.NewRGBA(image.Rect(0, 0, logoImg.Bounds().Dx()+pic2FramePadding, logoImg.Bounds().Dy()+pic2FramePadding))
// 图层颜色设为白色
draw.Draw(transparentImg, transparentImg.Bounds(), image.White, image.Point{}, draw.Over)
// 将缩略图放到透明图层上
draw.Draw(transparentImg,
image.Rect(pic2FramePadding/2, pic2FramePadding/2, transparentImg.Bounds().Dx(), transparentImg.Bounds().Dy()),
logoImg,
image.Point{},
draw.Over)
//logo和二维码拼接
draw.Draw(outImg, outImg.Bounds(), qrcodeImg, image.Pt(0, 0), draw.Over)
offset := image.Pt((outImg.Bounds().Max.X-transparentImg.Bounds().Max.X)/2, (outImg.Bounds().Max.Y-transparentImg.Bounds().Max.Y)/2)
draw.Draw(outImg, outImg.Bounds().Add(offset), transparentImg, image.Pt(0, 0), draw.Over)
buf := new(bytes.Buffer)
_ = png.Encode(buf, outImg)
// 写入文件
f, _ := os.Create(outPath)
_ = png.Encode(f, outImg)
res := base64.StdEncoding.EncodeToString(buf.Bytes())
return nil, res
}
func main() {
err, s := CreateQrCodeBs64WithLogo("https://blog.csdn.net/weihongyicui?spm=1001.2100.3001.5343",
"logo.jpg",
"qr.png", 512)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s)
}
函数会根据传入参数自动生成二维码图片文件,同时返回二维码的base64编码。
效果展示:
![](https://img-blog.csdnimg.cn/img_convert/ef0a73b3f3ab450bb02feba2a15f60d0.png)