Golang-9宫格头像生成


先看效果

  • 头像间有间隔
    在这里插入图片描述
  • 头像间无间隔
    在这里插入图片描述

代码

  1. 网络图片下载到本地

    func multiGetImages(urls []string, dir string, prefix string)(localPath []string){
     var w = sync.WaitGroup{}
     w.Add(len(urls))
     timestamp := time.Now().UnixNano()
     for i, url :=range urls {
         name := fmt.Sprintf("%s/%s_%d_%d.png", dir, prefix, timestamp, i)
         localPath = append(localPath, name)
         go downloadImage(url, name, &w)
     }
     w.Wait()
     return
    }
    func downloadImage(url string, imgName string, wg *sync.WaitGroup){
     defer wg.Done()
     out, err := os.Create(imgName)
     if err != nil {
         fmt.Println(err)
         return
     }
     defer out.Close()
     client := http.Client{Timeout: 2 * time.Second}
     resp, err := client.Get(url)
     if err != nil {
         fmt.Println(err)
         return
     }
     defer resp.Body.Close()
     pix, err := ioutil.ReadAll(resp.Body)
     if err != nil {
         fmt.Println(err)
         return
     }
     _, err = io.Copy(out, bytes.NewReader(pix))
     return
    }
  2. 图片拼接

    func imageCompose(imagePath string, localPaths []string, gap int) {
     imageSize := 80
     imageRow := int(math.Sqrt(float64(len(localPaths)))) // 根据传入图片数量判断行列数量
     imageCol := imageRow
     rowOffset := gap
     colOffset := gap
     backImg := imaging.New(imageSize*imageRow+gap*(imageCol+1), imageSize*imageCol+gap*(imageRow+1), color.NRGBA{255, 255, 255, 255})
     tempRow, tempCol := 1, 1
     for tempRow < imageRow+1 {
         for tempCol < imageCol+1 {
             imgIndex := imageCol*(tempRow-1) + tempCol - 1
             resizeImg, err := imaging.Open(localPaths[imgIndex])
             if err != nil {
                 fmt.Println(err)
             }
             resizeImg = imaging.Blur(imaging.Resize(resizeImg, imageSize, imageSize, imaging.Lanczos), 2) // 加了模糊操作
             backImg = imaging.Paste(backImg, resizeImg, image.Pt((tempCol-1)*imageSize+colOffset, (tempRow-1)*imageSize+rowOffset))
             tempCol += 1
             colOffset += gap
         }
         tempRow += 1
         rowOffset += gap
         tempCol = 1
         colOffset = gap
     }
     err := imaging.Save(backImg, imagePath)
     if err != nil {
         fmt.Println(err)
     }
     return
    }
  3. 删除临时图片

    func removeFile(filePaths []string){
     for _,url := range filePaths{
         err := os.RemoveAll(url)
         if err != nil {
             fmt.Println(err)
         }
     }
    }

评论
  目录