package image import ( "github.com/skip2/go-qrcode" "gopkg.in/gographics/imagick.v3/imagick" "icloudapp.cn/tools/util" "image/color" ) type QR struct { Cache Value string FrontColor string BackgroundColor string ViewSize *Size ViewPoint *Point Angle float64 } func NewQR() *QR { QRInstance := &QR{} QRInstance.SetSize(0, 0) QRInstance.SetViewPoint(0, 0) return QRInstance } func (q *QR) SetCache(path string) { q.Cache.SetCache(path) } func (q *QR) SetValue(value string) { q.Value = value } func (q *QR) SetFrontColor(frontColor string) { q.FrontColor = frontColor } func (q *QR) SetBackgroundColor(backgroundColor string) { q.BackgroundColor = backgroundColor } func (q *QR) SetSize(width, height uint) { q.ViewSize = NewSize(width, height) } func (q *QR) SetViewPoint(x, y float64) { q.ViewPoint = NewPoint(x, y) } // SetAngle 设置旋转角度 func (q *QR) SetAngle(angle float64) { q.Angle = angle } func (q *QR) Create() (*imagick.MagickWand, error) { if q.BackgroundColor == "" { q.BackgroundColor = "#000" } if q.FrontColor == "" { q.FrontColor = "#fff" } _, background, _ := Alpha(q.BackgroundColor) _, front, _ := Alpha(q.FrontColor) backgroundColor := color.RGBA{R: background.R, G: background.G, B: background.B, A: background.A} frontColor := color.RGBA{R: front.R, G: front.G, B: front.B, A: front.A} if q.ViewSize.Width == 0 { q.ViewSize.Width = 200 } qr, err := qrcode.New(q.Value, qrcode.Medium) if err != nil { return nil, err } qr.DisableBorder = true qr.ForegroundColor = frontColor qr.BackgroundColor = backgroundColor qrByte, err := qr.PNG(int(q.ViewSize.Width)) if err != nil { return nil, util.NewError("qr.PNG err : ", err.Error()) } qrWM := imagick.NewMagickWand() if err = qrWM.ReadImageBlob(qrByte); err != nil { return nil, util.NewError("qrWM.SetImageFilename err : ", err.Error()) } if err = qrWM.SetSize(q.ViewSize.Width, q.ViewSize.Height); err != nil { return nil, util.NewError("qrWM.SetSize err : ", err.Error()) } if q.Angle > 0 { if err = qrWM.RotateImage(OpacityPixel(), q.Angle); err != nil { return nil, util.NewError("qrWM.RotateImage err : ", err.Error()) } alignX := float64(qrWM.GetImageWidth()-q.ViewSize.Width) / 2 alignY := float64(qrWM.GetImageHeight()-q.ViewSize.Height) / 2 q.ViewPoint.X = q.ViewPoint.X - alignX q.ViewPoint.Y = q.ViewPoint.Y - alignY } return qrWM, nil }