golang在图片添加svg水印

347 阅读1分钟
import (
  "image"
  "image/png"
  "image/draw"
  "os"

  "github.com/srwiley/oksvg"
  "github.com/srwiley/rasterx"
)

func main() {
  // 读取图片地址
  resp, err := http.Get(url)  
  if err != nil {  
  fmt.Println("图片获取失败", err.Error())  
    return nil  
  }  
  defer resp.Body.Close()  
  img, _, err := image.Decode(resp.Body)  
  if err != nil {  
   fmt.Println("图片decode失败", err.Error())  
   return nil  
  }  
  
  w, h := img.Bounds().Bounds().Dx(), img.Bounds().Dy()

  // 读取svg
  in, err := os.Open("/a/b/water.svg")
  if err != nil {
    panic(err)
  }
  defer in.Close()

  // 创建图片背景
  newImg := image.NewNRGBA(img.Bounds())    
  draw.Draw(newImg, img.Bounds(), img, image.ZP, draw.Src)

  icon, _ := oksvg.ReadIconStream(in)
  // 设置水印位置xy和大小xy
  icon.SetTarget(float64(w/2), float64(h/2), 20, 10)
  icon.Draw(rasterx.NewDasher(w, h, rasterx.NewScannerGV(w, h, newImg, newImg.Bounds())), 1)

  out, err := os.Create("./out.png")
  jpeg.Encode(out, newImg, &jpeg.Options{100})
  if err != nil {
    panic(err)
  }
  defer out.Close()
}