package main import ( "fmt" "image" "image/draw" "image/jpeg" "net/http" "os" "strconv" "time" "github.com/nfnt/resize" "golang.org/x/sync/errgroup" ) func main() { img := strconv.Itoa(int(time.Now().UnixNano())) + ".jpeg" f, err := os.Create(img) if err != nil { fmt.Println("Create", err) return } // 把二维码图片合到海报上 rgba, err := MergeImageNew("http://img/16028328876241490.jpeg", "http://8134.jpg", 76, 436, 87) if err != nil { fmt.Println("MergeImageNew", err) return } err = jpeg.Encode(f, rgba, nil) if err != nil { fmt.Println("Encode", err) return } } // MergeImageNew 图片合并 baseUrl:原图图片地址,maskUrl:小图图片地址 func MergeImageNew(baseUrl, maskUrl string, paddingX int, paddingY int, width uint) (*image.RGBA, error) { eg := errgroup.Group{} var base image.Image eg.Go(func() error { var err error base, err = GetImageFromNet(baseUrl) return err }) mask, err := ImageZoom(maskUrl, width) if err != nil { return nil, err } if err = eg.Wait(); err != nil { return nil, err } baseSrcBounds := base.Bounds().Max maskSrcBounds := mask.Bounds().Max newWidth := baseSrcBounds.X newHeight := baseSrcBounds.Y maskWidth := maskSrcBounds.X maskHeight := maskSrcBounds.Y des := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight)) // 底板 //首先将一个图片信息存入jpg draw.Draw(des, des.Bounds(), base, base.Bounds().Min, draw.Over) //将另外一张图片信息存入jpg fmt.Println(newHeight, paddingY, maskHeight) draw.Draw(des, image.Rect(paddingX, paddingY, (paddingX+maskWidth), (maskHeight+paddingY)), mask, image.Point{}, draw.Over) return des, nil } // GetImageFromNet 从远程读取图片 func GetImageFromNet(url string) (image.Image, error) { res, err := http.Get(url) if err != nil || res.StatusCode != 200 { return nil, err } defer res.Body.Close() m, _, err := image.Decode(res.Body) return m, err } // ImageZoom 按宽度缩放图片 func ImageZoom(url string, width uint) (image.Image, error) { m, err := GetImageFromNet(url) if err != nil { return nil, err } if width == 0 { return m, nil } thImg := resize.Resize(width, 0, m, resize.Lanczos3) return thImg, nil }