All formats

oksvg

LanguageGo
LicenseBSD-3-Clause
Repositorygithub.com/srwiley/oksvg
Documentationpkg.go.dev
Depends onrasterx, golang.org/x/image, golang.org/x/net
Read / writeread (renders to any draw.Image) / no

oksvg parses SVG and draws it with rasterx, a scanline rasterizer that implements SVG 2 stroke features (including the arc line join). It’s pure Go and good enough for most icon sets: paths, basic shapes, groups, transforms, solid colors, linear and radial gradients, opacity and <use>.

It doesn’t render text, images, filters, masks, clipping or patterns, and supports only simple class selectors from a <style> element inside <defs>. Unknown elements cause errors in strict mode. The last changes are from 2022-2023, so treat it as stable but unmaintained. For broader coverage in pure Go see canvas.

Installation#

Shell
go get github.com/srwiley/oksvg github.com/srwiley/rasterx

Basic usage: render SVG to PNG#

Go
package main

import (
	"fmt"
	"image"
	"image/png"
	"log"
	"os"

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

func main() {
	icon, err := oksvg.ReadIcon("in.svg", oksvg.WarnErrorMode)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("viewBox %v x %v\n", icon.ViewBox.W, icon.ViewBox.H)

	w, h := int(icon.ViewBox.W), int(icon.ViewBox.H)
	icon.SetTarget(0, 0, float64(w), float64(h))

	img := image.NewRGBA(image.Rect(0, 0, w, h))
	scanner := rasterx.NewScannerGV(w, h, img, img.Bounds())
	icon.Draw(rasterx.NewDasher(w, h, scanner), 1.0) // 1.0 = full opacity

	out, err := os.Create("out.png")
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()
	if err := png.Encode(out, img); err != nil {
		log.Fatal(err)
	}
}

How to render an SVG icon at a given size#

SetTarget(x, y, w, h) maps the viewBox to a rectangle in the output image:

Go
size := 256
icon.SetTarget(0, 0, float64(size), float64(size))
img := image.NewRGBA(image.Rect(0, 0, size, size))
icon.Draw(rasterx.NewDasher(size, size, rasterx.NewScannerGV(size, size, img, img.Bounds())), 1.0)

For non-square icons, compute the height from icon.ViewBox.H / icon.ViewBox.W.

How to load SVG from memory#

Go
icon, err := oksvg.ReadIconStream(bytes.NewReader(svgData), oksvg.WarnErrorMode)

How to replace currentColor#

Icon sets often use fill="currentColor". ReadReplacingCurrentColor substitutes a color while parsing:

Go
f, _ := os.Open("icon.svg")
defer f.Close()
icon, err := oksvg.ReadReplacingCurrentColor(f, "#d33", oksvg.WarnErrorMode)

Tips#