fusenapi/utils/qrcode/creator.go

94 lines
2.8 KiB
Go
Raw Normal View History

2023-06-08 09:02:38 +00:00
package qrcode
import (
"bytes"
"encoding/base64"
"github.com/nfnt/resize"
"github.com/skip2/go-qrcode"
"golang.org/x/image/draw"
"image"
_ "image/jpeg"
"image/png"
"os"
)
2023-06-13 11:31:35 +00:00
// 带logo的二维码图片生成 content-二维码内容 size-像素单位 outPath 保存路径(传空则不保存) logoPath-logo文件路径(传空就不带) xx轴整体偏移 y:y轴整体偏移
2023-06-08 09:02:38 +00:00
func CreateQrCodeBs64WithLogo(content, outPath string, logoPath string, size, x, y int, disableBorder bool) (data string, err error) {
code, err := qrcode.New(content, qrcode.High)
if err != nil {
return
}
if disableBorder {
code.DisableBorder = true
}
//设置文件大小并创建画板
qrcodeImg := code.Image(size)
outImg := image.NewRGBA(qrcodeImg.Bounds())
buf := new(bytes.Buffer)
//无logo
if logoPath == "" {
//图像偏移
2023-06-08 10:22:27 +00:00
if x != 0 || y != 0 {
draw.Draw(outImg, outImg.Bounds().Add(image.Pt(x, y)), qrcodeImg, outImg.Bounds().Min, draw.Src)
}
_ = png.Encode(buf, outImg)
2023-06-08 09:02:38 +00:00
if outPath != "" {
// 写入文件
2023-06-13 11:38:32 +00:00
f, err := os.Create(outPath)
if err != nil {
return "", err
}
2023-06-08 09:02:38 +00:00
defer f.Close()
2023-06-08 10:22:27 +00:00
err = png.Encode(f, outImg)
2023-06-08 09:02:38 +00:00
if err != nil {
return "", err
}
}
return base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}
//读取logo文件
logoFile, err := os.Open(logoPath)
if err != nil {
return "", err
}
logoImg, _, err := image.Decode(logoFile)
if err != nil {
return "", err
}
logoImg = resize.Resize(uint(size/5), uint(size/5), 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)
//图像偏移
2023-06-08 10:22:27 +00:00
if x != 0 || y != 0 {
draw.Draw(outImg, outImg.Bounds().Add(image.Pt(x, y)), qrcodeImg, outImg.Bounds().Min, draw.Src)
}
2023-06-08 09:02:38 +00:00
err = png.Encode(buf, outImg)
if err != nil {
return "", err
}
if outPath != "" {
// 写入文件
f, _ := os.Create(outPath)
defer f.Close()
_ = png.Encode(f, outImg)
}
return base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}