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" ) // 带logo的二维码图片生成 content-二维码内容 size-像素单位 outPath 保存路径(传空则不保存) disableBorder是否不启用边框 logoPath-logo文件路径(传空就不带) x:x轴整体偏移 y:y轴整体偏移 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 == "" { //图像偏移 if x != 0 || y != 0 { draw.Draw(outImg, outImg.Bounds().Add(image.Pt(x, y)), qrcodeImg, outImg.Bounds().Min, draw.Src) } err = png.Encode(buf, outImg) if err != nil { return "", err } if outPath != "" { // 写入文件 f, err := os.Create(outPath) if err != nil { return "", err } defer f.Close() err = png.Encode(f, outImg) 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) //图像偏移 if x != 0 || y != 0 { draw.Draw(outImg, outImg.Bounds().Add(image.Pt(x, y)), qrcodeImg, outImg.Bounds().Min, draw.Src) } err = png.Encode(buf, outImg) if err != nil { return "", err } if outPath != "" { // 写入文件 f, err := os.Create(outPath) if err != nil { return "", err } defer f.Close() err = png.Encode(f, outImg) if err != nil { return "", err } } return base64.StdEncoding.EncodeToString(buf.Bytes()), nil }