如何创建和导出 svg 到 png/jpeg

Yat*_*ngh 8 canvas imagemagick go

我有以下代码片段,例如

package main

import (
    "github.com/ajstarks/svgo"
    "os"
    _ "image"
    _ "fmt"
)

func main(){
    width := 512
    height := 512

    canvas := svg.New(os.Stdout)
    canvas.Start(width,height)
    canvas.Image(0,0,512,512,"src.jpg","0.50")
    canvas.End()
}
Run Code Online (Sandbox Code Playgroud)

我想将由此代码创建的 svg 导出为 jpeg 或 png 或 svg 比方说。如何做到这一点我不明白。我可以使用 imagemagick 或其他东西,但为此我需要 SVG 的东西。请有人帮我解决这个问题。

小智 7

如果您更喜欢使用纯 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)
  }
}
Run Code Online (Sandbox Code Playgroud)