Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and export svg to png/jpeg

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.

like image 673
Yatender Singh Avatar asked Mar 24 '17 07:03

Yatender Singh


People also ask

Can you save SVG as JPG?

Export as a new file typeIf your SVG is a single framed image, load the file up into your image editor. Then select the Export option and choose JPG as your file type. You may be asked about the resolution or preservation quality you desire, or your program may save directly to the file you need.

Which is better JPEG or PNG or SVG?

JPEG image is generally smaller than PNG image of same image. SVG image is generally larger than JPEG image of same image. JPEG images are not editable. SVG images are text based and are easy to edit.

How do I save an SVG as a picture?

RIGHT CLICK on the LINK to the SVG image as shown below. In this example, you would right click on the text “SVG Format”. You would then select the option “Save Link As” (the exact wording varies from one browser to the next) to save the image.


2 Answers

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)
  }
}
like image 184
Usual Human Avatar answered Oct 26 '22 20:10

Usual Human


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)

like image 43
Benjamin Kadish Avatar answered Oct 26 '22 20:10

Benjamin Kadish