8

I have following code snippet for e.g.

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()
}

I want to export svg created by this code to jpeg or png or svg let's say. How to do that I am not getting idea. I can use imagemagick or something but for that I need SVG thing. please someone help me with this.

Yatender Singh
  • 3,098
  • 3
  • 22
  • 31
  • may I know the reason of downvoting whoever has downvoted it? – Yatender Singh Jun 20 '17 at 05:50
  • Golang is very easy to combine with Javascript. You may consider using Javascript to do that, and if necessary, you can still send it with [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data) to communicate with Go. I build a [script](https://stackoverflow.com/a/68398009/9935654) to convert SVG to PNG by Javascript you can do some modifications to achieve. – Carson Jul 18 '21 at 12:49

2 Answers2

6

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)
  }
}
Usual Human
  • 76
  • 1
  • 2
  • thanks! is it okay if I use your code here? (Code comment links to your user profile and to this question.) https://github.com/trashhalo/imgcat/pull/16/files – mh8020 Nov 11 '20 at 22:16
  • To make the code more generic, remove the `w, h := 512, 512` and add `w := int(icon.ViewBox.W) h := int(icon.ViewBox.H)` Directly after the `icon, _ := oksvg.ReadIconStream(in)` – Nigel Ainscoe Mar 16 '21 at 11:14
3

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)

Benjamin Kadish
  • 1,472
  • 11
  • 20