How to create and export svg to png/jpeg in golang

To output an .svg file just pass a file Writer to svg.New

f, err := os.Create("my_new_svg.svg")
... handle error
canvas := svg.New(f)

This will save your output in my_new_svg.svg. Once you have done this you can open in your favorite web browser etc. I'd guess the easiest way to get a .png or .jpeg is to use some external tool (like Image Magick)


If you prefer using pure go

package main

import (
  "image"
  "image/png"
  "os"

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

func main() {
  w, h := 512, 512

  in, err := os.Open("in.svg")
  if err != nil {
    panic(err)
  }
  defer in.Close()

  icon, _ := oksvg.ReadIconStream(in)
  icon.SetTarget(0, 0, float64(w), float64(h))
  rgba := image.NewRGBA(image.Rect(0, 0, w, h))
  icon.Draw(rasterx.NewDasher(w, h, rasterx.NewScannerGV(w, h, rgba, rgba.Bounds())), 1)

  out, err := os.Create("out.png")
  if err != nil {
    panic(err)
  }
  defer out.Close()

  err = png.Encode(out, rgba)
  if err != nil {
    panic(err)
  }
}