1

SVG Path to PNG

by
Published Nov 18, 2022

Convert a SVG path to a PNG file.

Script helper
  • Submitted by jaller94 Go
    Created 1314 days ago
    1
    import (
    2
    	"encoding/base64"
    3
    	"io/ioutil"
    4
    	"github.com/tdewolff/canvas"
    5
    	"github.com/tdewolff/canvas/renderers"
    6
    )
    7
    
    
    8
    // This is just an example. To convert your own SVG path to a PNG file, you need
    9
    // to adapt the script.
    10
    func main() (interface{}, error) {
    11
    	// Create new canvas of dimension 400x400 mm
    12
    	c := canvas.New(400, 400)
    13
    
    
    14
    	// Create a canvas context used to keep drawing state
    15
    	ctx := canvas.NewContext(c)
    16
    
    
    17
    	// Create a triangle path from an SVG path and draw it to the canvas
    18
    	path, err := canvas.ParseSVG("M150 0 L75 200 L225 200 Z")
    19
    	if err != nil {
    20
    		panic(err)
    21
    	}
    22
    	ctx.SetFillColor(canvas.Mediumseagreen)
    23
    	ctx.DrawPath(20, 20, path)
    24
    
    
    25
    	renderers.Write("tmp.png", c, canvas.DPMM(1.0))
    26
    
    
    27
    	content, err2 := ioutil.ReadFile("tmp.png")
    28
    	if err2 != nil {
    29
    		panic(err)
    30
    	}
    31
    	output := base64.StdEncoding.EncodeToString([]byte(content))
    32
    
    
    33
    	return output, nil
    34
    }