Skip to content

Instantly share code, notes, and snippets.

@abdullahnettoor
Last active February 27, 2025 19:33
Show Gist options
  • Select an option

  • Save abdullahnettoor/98b2911d9af4e0a875f7370926d81a86 to your computer and use it in GitHub Desktop.

Select an option

Save abdullahnettoor/98b2911d9af4e0a875f7370926d81a86 to your computer and use it in GitHub Desktop.
SVG to PNG Converter in Go
// This Go utility function, svgToPng, converts an SVG file into a PNG image with a
// specified width and height. It leverages the oksvg and rasterx libraries to parse
// and render the SVG before encoding it as a PNG.
// The script ensures proper file handling and error management, making it a reusable
// and efficient solution for SVG-to-PNG conversion.
// The main function provides an example usage, converting pb_mono.svg into out.png at 512x512 resolution.
package main
import (
"image"
"image/png"
"os"
"github.com/srwiley/oksvg"
"github.com/srwiley/rasterx"
)
// svgToPng converts an SVG file to a PNG file with the specified width and height.
func svgToPng(inputFile, outputFile string, width, height int) error {
in, err := os.Open(inputFile)
if err != nil {
return err
}
defer in.Close()
icon, err := oksvg.ReadIconStream(in)
if err != nil {
return err
}
icon.SetTarget(0, 0, float64(width), float64(height))
rgba := image.NewRGBA(image.Rect(0, 0, width, height))
icon.Draw(rasterx.NewDasher(width, height, rasterx.NewScannerGV(width, height, rgba, rgba.Bounds())), 1)
out, err := os.Create(outputFile)
if err != nil {
return err
}
defer out.Close()
return png.Encode(out, rgba)
}
func main() {
if err := svgToPng("in.svg", "out.png", 512, 512); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment