package image import ( "context" "fmt" "gopkg.in/gographics/imagick.v3/imagick" "icloudapp.cn/tools/util" "strings" ) type Poster struct { ctx context.Context } func NewPoster(ctx context.Context) *Poster { return &Poster{ctx: ctx} } func (p *Poster) Text(item Items) (*imagick.MagickWand, Items, error) { var updated Items item.Value = strings.Replace(item.Value, " ", " ", -1) txt := NewText(item.Font, float64(item.Size), "") txt.SetText(item.Value) txt.SetColor(item.Color) txt.SetBackground(item.Background) txt.SetSize(item.Width, item.Height) txt.SetPoint(float64(item.X), float64(item.Y)) txt.SetAlign(*item.Align) txt.SetBius(*item.Bius) txt.SetAngle(int64(item.Angle)) if *item.Wrap { txt.SetWrap(*item.Wrap) } mw, err := txt.Create() updated = item updated.X = int(txt.Coordinate.X) updated.Y = int(txt.Coordinate.Y) updated.Width = txt.ViewSize.Width updated.Height = txt.ViewSize.Height return mw, updated, err } func (p *Poster) QRCode(item Items) (*imagick.MagickWand, Items, error) { var updated Items cachePath := fmt.Sprintf("%s/cache", util.Getwd()) qr := NewQR() qr.SetValue(item.Value) qr.SetSize(item.Width, item.Height) qr.SetBackgroundColor(item.Background) qr.SetFrontColor(item.Color) qr.SetCache(cachePath) mw, err := qr.Create() updated = item return mw, updated, err } type PosterMW struct { Index int Image *imagick.MagickWand Item Items Err error } func (p *Poster) Create(json PosterJson) (*imagick.MagickWand, error) { cachePath := fmt.Sprintf("%s/cache", util.Getwd()) image := NewImage(util.Getwd()) image.SetCache(cachePath) if json.Use == "bgUrl" { json.Background = "" } if json.Use == "bgc" { json.BackgroundUrl = "" } poster, err := image.Create(json.BackgroundUrl, json.Background, *NewSize(json.Width, json.Height)) if err != nil { return nil, err } itemLen := len(json.Items) destChan := make(chan *PosterMW, itemLen) defer close(destChan) for index, item := range json.Items { go func(item Items, index int) { var drawErr error var drawMW *imagick.MagickWand if item.Type == "text" { drawMW, item, drawErr = p.Text(item) } if item.Type == "image" { drawMW, drawErr = image.Resize(item.Value, item.Width, item.Height, item.Angle) } if item.Type == "qrcode" { drawMW, item, drawErr = p.QRCode(item) } destChan <- &PosterMW{Index: index, Image: drawMW, Item: item, Err: drawErr} }(item, index) } var response = make([]*PosterMW, itemLen) for i := 0; i < len(json.Items); i++ { res := <-destChan response[res.Index] = res } for i := 0; i < len(response); i++ { draw := response[i].Image errDraw := response[i].Err if errDraw != nil { continue } if response[i].Item.Type == "text" { fmt.Println(fmt.Sprintf("response[i].Item : %+v", response[i].Item)) } if errComposite := poster.CompositeImage(draw, imagick.COMPOSITE_OP_OVER, true, response[i].Item.X, response[i].Item.Y); errComposite != nil { fmt.Println("poster.CompositeImage text err : ", errComposite.Error()) continue } } return poster, nil }